Override private method

落爺英雄遲暮 提交于 2020-01-22 16:24:43

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/15602549/override-private-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!