Search

Wednesday, June 1, 2011

Rule to remember : Overrriding in Java


package SCJP;

/* A way to inherit behavior(function) of base class by sub class is called overriding
 * 1.visibility can not reduce in overriding
 * public -> private (Wrong)
 * private -> protected , public (Right)
 *
 * 2. Exceptions can be allow in specialized manner or none(super -> subclass)
 * RuntimeExcept -> Excpetion , RuntimeException (right)  
 *
 */
class override1 {
int show(int k) throws RuntimeException, Exception { return 0;}

public int show(String l){return 1;}
}

class override2 extends override1 {
//private int show(int j) throws RuntimeException{return 9;}
protected int show(int k) throws Exception  {return 3;}
}

public class overrideDemo {

public static void main(String args[]) {
override1 ov1 = new override2();
try {
try {
System.out.println(ov1.show(6));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


No comments:

Post a Comment