NoviceCai
NoviceCai

Reputation: 612

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

Upvotes: 4

Views: 3197

Answers (3)

AmitG
AmitG

Reputation: 10543

You can simply write a private method in subclass but it will not be overridden. But it still follows access modifier rules which are used in overriding

If you make wider access modifier(default, protected, public) in superclass method when subclass's method is private then compiler shows errors. It follows overriding rule but doesn't override actually.

Upvotes: 0

millimoose
millimoose

Reputation: 39950

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.

Upvotes: 4

Keppil
Keppil

Reputation: 46209

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.

Upvotes: 12

Related Questions