Hello, please check out the code as follows. Why is i=0? Thomas class Top { public Top() {setvalue();} int i; // private void setvalue() protected void setvalue() { i = 2; System.out.println("Top i =" + i); } protected int getvalue() {return i;} } class Bottom extends Top { int j; public Bottom() {setvalue();} // private void setvalue() protected void setvalue() { j = 3; System.out.println("Bottom j =" + j); } // protected int getvalue() {return j;} } public class RunIt1a { public static void main(String[] args) { Top b = new Bottom(); Top T = new Top(); System.out.println( "i = " + T.getvalue() ); System.out.println( "i = " + b.getvalue() ); } }
C:\jdk1.3\bin>java RunIt1a Bottom j =3 Bottom j =3 Top i =2 i = 2 i = 0 WHY Is I = 0 and not 2?
When new Bottom is called the constuctor of Bottom is called which calls Top's default constructor. In the default constructor u have called setValue(). The setvalue method invoked in the Top's constructor will be that of subclass(u have overriden setValue in Bottom class) since u are creating a instance od Bottom and not of Top.so j =3 and i is still 0 . In the print statement u are calling getValue.Since there is only one getValue method in superclass that method is called and the correct value 0 is printed.