class Penguin {
public static int getHeight() {
return 3;
}
public void printInfo() {
System.out.println(this.getHeight());
}
}
public class CrestedPenguin extends Penguin {
public static int getHeight() {
return 8;
}
public static void main(String... fish) {
new CrestedPenguin().printInfo();
}
}
This code output 3.
I don't understand the output. I expected 8 because of method hiding.
I looked on the internet for method hiding and I understand this concept, but I don't understand why the getHeight
method called is the one in Penguin instead of the one in Crested Penguin
since the reference is of a CrestedPenguin
type.
Update: i want to mention that this is an educational code and it is not intended for production purpose. I am preparing for the Java OCP.
The problem with this code snippet is that you added
static
keyword ingetHeight()
function. We cannot override static function because we don't need an object to access the function. Changing it toWill override
getHeight()
function of Penguin.