There are two programms:
First programm:
a is an instance variable which is overwritten in subclass:
class Super
{
int a=2;
Super() {printone();}
void printone() { System.out.println("Inside Super "+a+"\n");}
}
public class Sub3 extends Super
{
int a=3; //***************************
void printone() {System.out.println("Inside Sub3 "+a);}
public static void main(
String arg[])
{
Sub3 s = new Sub3();
s.printone();
}
}
Result:
Inside Sub3 0
Inside Sub3 3
Before creating subclass object Sub3 the superclass Super is
initialized by automatically inserted call to superclass
constructor super().
In superclass constructor super is a method call to printone().
As we have dynamic binding JVM realizes that s is a Sub3 object
and invokes Sub3-printone() method.
In Sub3-printone JVM prints a (Sub3) which is declared with
default value (0) and not initialized to 3 as Sub3-constructor
has not been executed yet.
Therefore result in line 1 is: Inside Sub3 0
Result in line 2 is: Inside Sub3 3
as Sub3 a has been fully initialised;
NOW MY QUESTION:
Second program:
class Super
{
int a=2;
Super() {printone();}
void printone() { System.out.println("Inside Super "+a+"\n");}
}
public class Sub3 extends Super
{
{int a=3;} //NOW Instance initializer *******************
void printone() {System.out.println("Inside Sub3 "+a);}
public static void main(String arg[])
{
Sub3 s = new Sub3();
s.printone();
}
}
The result is:
Inside Sub3 2
Inside Sub3 2
The declaration in Sub3 has been changed from a=3 to {a=3;}
which is an instance initializer;
The result for line 1 should be: Inside Sub3 3
but it is "Inside Sub3 2"
It seems that subclass instance variable a has been
declared and inititalized to a=3 and then been overwritten
by superclass a=2?
WHY?
Appreciate your answers.
Thomas
------------------