Dear friends This is my first posting in java ranch ,i have problem in follwing code class Base{ public int i=10; public int getI() { return this.i; } } class Derived1 extends Base { public int i=20; public int getI() { return this.i; } } public class Derived { public static void main(String[] args){ Base b = new Derived1(); System.out.println("b.i"+ b.i ); System.out.println("b.getI()" + b.getI()); } }
my question is when i print System.out.println("b.i"+ b.i ); it is printing b.i 10 why becouse i am making object of drived class so it shoul print b.i 20 but when i printing b.getI() it is printing 20 why ??? please descirbe in detail thnx
Anshuman Acharya
Ranch Hand
Joined: Jan 19, 2001
Posts: 144
posted
0
polymorphism is only for overridden non-static methods. fields and static methods don't get overridden, they just get hidden. from desborough's note: Fields do not act polymorphically: - whenever you access a field from outside the class, the declared type of the reference is used rather than the type of the object it refers to. - regardless of the type of the reference, a method will always access its own fields rather than those of a derived class. refer to any good book and you'll find the answer
deep_scjp
Greenhorn
Joined: Jan 04, 2001
Posts: 12
posted
0
thnx Anshuman i got your answer,
Ajith Kallambella
Sheriff
Joined: Mar 17, 2000
Posts: 5782
posted
0
Your name "deep_scjp" does not comply with the JavaRanch naming policy. Please choose one that meets the requirements.
------------------ Ajith Kallambella M. Sun Certified Programmer for the Java�2 Platform.
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).