Slight confusion regarding overriding where variables are concerned

Although the override is done properly for SubCovariantTest the answer is 5 because of how the variable c1 is declared. It is declared as a CovariantTest and not as a SubCovariantTest.

When c1.getObject().x is run, it does not know that it is a SubCovariantTest (no casting was used). This is why 5 is returned from CovariantTest and not 6 from SubCovariantTest.

If you change

System.out.println(c1.getObject().x);

to

System.out.println(((SubCovariantTest) c1).getObject().x);

you will get 6 as you expected.

Edit: As pointed out in the comments

“fields are not polymorphic in Java. Only methods are. The x in the subclass hides the x in the base class. It doesn’t override it.” (Thanks to JB Nizet)

Leave a Comment