I’m training for a Java exam, and I’ve come across something I don’t understand in last year subject. Here is the code
class Mother {
int var = 2;
int getVar() {
return var;
}
}
class Daughter extends Mother {
int var = 1;
int getVar() {
return var;
}
public static void main(String[] args) {
Mother m = new Mother();
System.out.println(m.var);
System.out.println(m.getVar());
m = new Daughter();
System.out.println(m.var);
System.out.println(m.getVar());
}
}
The question is “what is the output of this program?”. I would have go with 2 2 1 1, but when compiling and running this piece of code, I get 2 2 2 1.
Anyone can explain me why ?
Thanks for reading !
The method call
m.getVar()is a virtual method call. The second time you call it, it’s dynamically dispatched to the derivedDaughter.getVar(), which does what you expect (accessesDaugther.varand returns that).There is no such virtual dispatch mechanism for member fields. So
m.varalways refers toMother.var, i.e. the base class’s version of that variable.The
Daughterclass can be seen as having two differentvarmember: the one fromMotherand its own. Its own member “hides” the one inMother, but can be accessed from within theDaughterclass by usingsuper.var.The official spec for this is in section 8.3 Field Declarations of the JLS.
Quote:
Note that it can get pretty interesting (emphasis added):
And:
So that paragraph is well worth reading 🙂