I am taking a practice test for Java certification and got this question:
What will the following code print?
class Baap {
public int h = 4;
public int getH() {
System.out.println("Baap "+h);
return h;
}
}
class Beta extends Baap {
public int h = 44;
public int getH() {
System.out.println("Beta " + h);
return h;
}
public static void main(String[] args) {
Baap b = new Beta();
System.out.println(b.h + " " + b.getH());
Beta bb = (Beta) b;
System.out.println(bb.h + " " + bb.getH());
}
}
This is the answer:
Beta 44
4 44
Beta 44
44 44
My question: why is the 4 from the main class returned instead of the 44 from child class? Shouldn't it return 44?
I also don't see any variable that is shadowed by another variable with the same name that is closer in scope.
(Sorry for my english. I am French speaking.)