So I was wondering about how classes instances are built.
public abstract class test {
int count;
public test(){
count();
count();
System.out.println("test" + this.count);
}
abstract void count();
}
public class derive extends test{
int count;
public derive(){
System.out.println("derive");
}
@Override
public void count(){
count++;
}
}
public static void main(String[] args) {
derived o = new derived();
}
The output is:
test0
derive
How come count = 0? and not 2?
The superclass constructor is called first. It calls count()
twice. With polymorphism, count()
in derive
is called, incrementing count
to 2
. What is incremented is the count
variable in derive
, because that what the simple name count
means in the subclass. The count
variable in test
is hidden by the count
in derive
.
However, the print statement refers to the count
in scope in the superclass, which is still 0
.
Note that when the superclass constructor finishes, then the subclass constructor body can finally execute. This includes giving all instance variables initial values. Here, even though count
is already 2
, it is "initialized" to 0
anyway. So even if you add a print statement in the subclass constructor, you'll still get 0
for count
there too.
To get a count
of 2
, remove the count
in derive
and change the count
in test
to be protected
or package-private (no access modifier). This will make count()
increment the variable count
in test
.