Look at the code below :
class Rodent {
protected int tailLength = 4;
public void getRodentDetails() {
System.out.println(this.tailLength);
}
}
public class Mouse extends Rodent {
protected int tailLength = 8;
public static void main(String[] args) {
Mouse mouse = new Mouse();
mouse.getRodentDetails();
}
}
Now getRodentDetails()
is inherited.
When it is called by a Mouse
reference , this.tailLength
should print 8
and not 4
as parent tailLength
is hidden in mouse.
Why does it print 4 ?
EDIT : The question is not about what is variable hiding and not also about how to try to override variables. The closest answer was given by JB Nizet in comments which I have expanded below as answer.