public MyOverRidingDemo() { super(); // TODO Auto-generated constructor stub A obj=new B();
obj.add(); System.out.println("Value Of I : "+obj.i); }
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new MyOverRidingDemo(); }
} class A { int i=10; public void add(){ System.out.println("Add() in Class A"); } }
class B extends A { int i=20; public void add(){ System.out.println("Add() in Class B"); } }
When i run this program, the out put is as follows :
Add() in Class B Value Of I : 10
It is pretty clear that B is overriding the add() method of Class A.
When an instance of B is made and assigned to a variable of type A,
obj.add() should refer to add of B
and obj.i should refer to i of B.
but over here..why is it Referring to i Of A???
"The greatest pleasure in life is doing what people say you cannot do." - Walter Bagehot
Amit Biswas
Ranch Hand
Joined: Jun 01, 2006
Posts: 52
posted
0
Naresh, Overriding applies to instance methods only. For static methods and instance variables, you can only hide the parent class equivalent in the method. If you add a getter for the 'i' variable in yor super-class and override the same in sub-class, like the following:
class SuperClass { public int i = 10; public int getVal(){ return i; } } class SubClass { public int i = 5; //hiding the superclass value public int getVal() { //overrding the super class method return i; //returns 5 since it has shadowed the superclass value of 10 } } ..... public static void main(String [] args) { SuperClass obj1 = new SuperClass(); SuperClass obj2 = new SubClass(); SubClass obj3 = new SubClass();
syout(obj1.i); //will print 10 since the reference type is SuperClass sysout(obj1.getVal()); //will print 10 since object type is SuperClass
syout(obj2.i);//will print 10 since reference type is SuperClass sysout(obj2.getVal());//will print 5 since object type is SubClass
syout(obj3.i); //will print 5 since reference type is SubClass sysout(obj3.getVal()); //will print 5 since object type is SubClass
}
Basically, you redefine an instance variable in a subclass and NOT override them. The same is true for static methods and fields as well.
Amit Biswas
Ranch Hand
Joined: Jun 01, 2006
Posts: 52
posted
0
A correction: Read
you can only hide the parent class equivalent in the method
as you can only hide the parent class equivalent in the subclass
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.