Javaの:親クラスからコール子クラスのメソッドインタフェースを使用して

android_griezmann:

この質問が有効であるか、私は親クラスの構造を定義すると何か間違ってやっているかどうかは知りません。

しかし、以下では、クラスの形成であり、インタフェースがあります。

public interface Test {
    public void print();
    public void write();
}

class Parent implements Test{
    @Override
        public void print() {
            System.out.print("This is parent class");
    }

    @Override
        public void write() {
            System.out.print("This is write method in parent class");
    }
 }

class Child extends Parent{
    @Override
    public void print(){
        System.out.print("This is child class);
    }
}

私はインターフェイスを使用してメソッドを呼び出す期待出力

Test test = new Parent();
test.print();

これは、子クラスからprintメソッドを呼び出す必要があります。

そして、私はインターフェイスを使用してメソッドを呼び出すとき

Test test = new Parent();
test.write();

これは、親クラスからのwriteメソッドを呼び出す必要があります。

だから、今、それは親クラスからメソッドを呼び出している場合の両方で、起こっていません。

だから、任意の提案や答えがはるかに高く評価されています。

デイブ:

使用すると:

Test test = new Parent();
test.write();

あなたはtest型であるParentとの認識していませんChildしたがって、あなたの出力は、上の両方の方法を示しているParentクラスが呼び出されます。

試してみてください。

Test test = new Child();
test.print();   // Will call Child::print()
test.write();   // Will call Parent::write()

そしてあなたが望むものを達成する必要があります。

NBは仕事に、このためには、追加する必要がありwrite()、あなたにTestこのように、インターフェース:

public interface Test {
    public void print();
    public void write(); // This is required for it to be accessible via the interface
}

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=478700&siteId=1