Reputation: 65
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?
Upvotes: 3
Views: 67
Reputation: 1212
derived count is 2 while test's count always is 0 as what you called count()
is the derived method instead of test's one.
Upvotes: 1
Reputation: 178253
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
.
Upvotes: 2
Reputation: 201429
Because you have two variables named count
. One that is visible in test
(but shadowed) by the one that is in derive
. Remove int count
from derive
and mark it protected
in test
.
Upvotes: 4