abstract class D {String s1 = "D"; String getS1() {return s1;}} class E extends D {String s1 = "E"; String getS1() {return s1;}} class F { public static void main (String[] s) { D x = new E(); System.out.print(x.s1 + x.getS1()); }}
I was Expecting EE output but the output is DE please Explain How
Originally posted by Akhilesh Yadav: abstract class D {String s1 = "D"; String getS1() {return s1;}} class E extends D {String s1 = "E"; String getS1() {return s1;}} class F { public static void main (String[] s) { D x = new E(); System.out.print(x.s1 + x.getS1()); }}
I was Expecting EE output but the output is DE please Explain How
Just remember that variable is determined during compile time (instance x is type D) and which method get invoke is determined during runtime (the actual object is type E as you expected). hth.
The o/p is quite obvious. Run time polymorphism is only for methods and not instance variables. Which variable called will depend on the reference type at compile time. Hence the O/P DE.
SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Variable depened upon the instance where as Method depends upon the Type of Object created. So here the instance is of Type D, which outputs the s1 as "D" . Object Type is of E,which calls the method in it,takes the instance variable of it,that is s1 as "E" and so prints E. Hope your dount got cleared.
Thanks Harish
Harish Paravasthu
Could you hold this kitten for a sec? I need to adjust this tiny ad:
a bit of art, as a gift, the permaculture playing cards