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.
CodePudding user response:
The problem with this code snippet is that you added static
keyword in getHeight()
function. We cannot override static function because we don't need an object to access the function. Changing it to
class Penguin {
public int getHeight() { return 3; }
public void printInfo() {
System.out.println(this.getHeight());
}
}
public class CrestedPenguin extends Penguin {
public int getHeight() { return 8; }
public static void main(String... fish) {
new CrestedPenguin().printInfo();
}
}
Will override getHeight()
function of Penguin.
CodePudding user response:
Since you mentioned that you are preparing for the OCP exam... I would like to expand what causes the method hiding behavior, in case you face similar problems:
The following list summarizes the five rules for hiding a method:
- The method in the child class must have the same signature as the method in the parent class.
- The method in the child class must be at least as accessible or more accessible than the method in the parent class.
- The method in the child class may not throw a checked exception that is new or broader than the class of any exception thrown in the parent class method.
- If the method returns a value, it must be the same or a subclass of the method in the parent class, known as covariant return types.
- The method defined in the child class must be marked as static if it is marked as static in the parent class (method hiding). Likewise, the method must not be marked as static in the child class if it is not marked as static in the parent class (method overriding).
This is quoted from "OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1", I suggest reading it for preparing for OCP, because it covers in all possible details the core features of Java, unlike the OCP books I've seen.