I thought I understood the concept of shadowing. But this Code made me wonder:
public class Counter {
int count = 0;
public void inc() {
count++;
}
public int getCount() {
return count;
}
}
class StepCounter extends Counter {
int count = 0;
int step = 1;
public StepCounter(int step) {
this.step = step;
}
public void inc() {
count += step;
}
}
StepCounter sc = new StepCounter(2);
sc.inc();
sc.inc();
System.out.println(sc.getCount());
System.out.println(sc.count);
So basically the Static Type of sc is StepCounter
.
It's counter is incremented twice, so it's at 4 after the first two commands.
My count Variable is not a private one, it is package private (since I haven't declared any visibility on it).
So if I call the .getCount()
method on sc, it first looks for it in StepCounter. There is none, so it goes to Counter. Here it finds the getCount()
method.
that method returns count. If count had been static or private, I'd understand why it returns 0. But why does it return 0 in this case? Even if I made the variable count public in StepCounter
, the result would still be 0.