I have this demo code:
class Test2 extends Test {
public int number = 0;
@Override
public void set(){
number = 1;
info();
}
@Override
public void info(){
System.out.println(number);
}
}
public class Test {
public Test(){
set();
}
public void set(){
}
public void info(){
}
public static void main(String[] args){
Test2 object = new Test2();
object.info();
}
}
The code gives this output:
1
0
Why? I expect this output:
1
1
In my opionion, the main function calls a constructor of Test2 class to create an object. The constructor calls automatically superclass’ constructor. This constructor calls method set() which is overridden. Therefore method set() of class Test2 is called. This method sets the field and calls info() method which writes the number. Then the main function calls the info() method of the created object again.
The number field is correctly set as the first line output is “1”. But why the second line contains 0? It seems that the field was not set at all. Can you explain it?
What should I do to get the behaviour I expect? Thanks in advance!
is equivalent to
So through invoking the super constructor the field
numberis set to 1. After the return from the super constructor, your assignment ofnumberto 0 is executed.Just remove the assignment and it should behave as you expect.