4

「Thinking in Java」を読んでいて疑問があります。「クラスの再利用」の章の「最終およびプライベート」セクションでは、プライベートメソッドをオーバーライドできないと述べています。しかし、私はマシンでそれを試しました。実際にはオーバーライドできます。

コードは次のとおりです。

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();
     }
}

それは印刷します:

カエルで

4

3 に答える 3

12

オーバーライドせず、同じ名前の新しいメソッドで 隠しただけです。

print()新しいメソッドを作成しなかった場合、Frogクラスにはメソッドがありません。

于 2013-03-24T18:52:58.047 に答える
4

オーバーライドと非表示の違いを説明するために、次のことを考慮してください。

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
    }
}

「オーバーライド」(つまり、非表示) メソッドは呼び出されず、親クラスのメソッドが呼び出されます。つまり、実際にはオーバーライドではないということです。

于 2013-03-24T18:57:47.820 に答える
0

privateメソッドを単純に記述できますが、subclassオーバーライドされません。ただし、オーバーライドで使用されるアクセス修飾子規則に従います

メソッドが非公開のときにメソッドを広くaccess modifier(デフォルト、保護、公開)すると、コンパイラでエラーが表示されます。オーバーライド規則に従いますが、実際にはオーバーライドしません。superclasssubclass's

于 2013-03-24T19:32:10.340 に答える