I am reading "Thinking in Java" and have a doubt. In the chapter "reusing classes", section "final and private", it says that a private method cannot be overridden. However, I tried it on the machine. It actually could be overridden.
Here is the code:
class Amphibian {
private void print() { System.out.println("in Amphibian"); }
}
public class Frog extends Amphibian {
public void print() { System.out.println("in Frog"); }
public static void main(String[] args) {
Frog f = new Frog();
f.print();
}
}
That prints:
in Frog
You didn't override it, you just hid it with a new method with the same name.
If you didn't create a new print()
method, your Frog
class wouldn't have one.
To illustrate the difference between overriding and hiding, consider this:
class Amphibian {
private void print() { System.out.println("in Amphibian"); }
public void callPrint() {
/*
* This will DIRECTLY call Amphibian.print(), regardless of whether the
* current object is an instance of Amphibian or Frog, and whether the
* latter hides the method or not.
*/
print(); // this call is bound early
}
}
class Frog extends Amphibian {
public void print() { System.out.println("in Frog"); }
public static void main(String[] args) {
Frog f = new Frog();
f.callPrint(); // => in Amphibian
// this call is bound late
f.print(); // => in Frog
}
}
The "overriding" (i.e. hiding) method doesn't get called, the one in the parent class does. Which means it's not really an override.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With