Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override private method

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

like image 883
NoviceCai Avatar asked Dec 05 '22 11:12

NoviceCai


2 Answers

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.

like image 191
Keppil Avatar answered Jan 01 '23 21:01

Keppil


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.

like image 35
millimoose Avatar answered Jan 01 '23 20:01

millimoose