class Alpha {
int over =1;
public int getOver() {
return over;
}
}
class Beta extends Alpha {
int over = 2;
public int getOver() {
return over;
}
}
public class Gamma extends Beta {
int over = 3;
public static void main(
String[] args) {
new Gamma().go();
}
public int getOver() {
return over;
}
void go() {
Beta b = new Gamma();
Alpha a = new Gamma();
//statement 1
System.out.println(super.over+" "+b.over+ " "+a.over);
//statement 2
System.out.println(super.getOver()+" "+b.getOver()+ " "+a.getOver());
}
}
I fell for this one last night in the mock
test, as with overriding, VARIABLES are not overridden, only METHODS are. I have added in the methods to illustrate the perceived expected response of overriding and
polymorphism,
you should be able to get this running on your pc.
Statement 1 is part of the test, and the result looks like it could be 2 3 3 however its actually 2 2 1, as the object is referring to variables and not methods. However Statement 2 shows what we might have expected with overridden methods. 2 3 3. And you can not clearly see the difference.
The fact that the variable "over" is repeated is an example of shadowing