簡體   English   中英

覆蓋父 Class 和接口中存在的方法(具有相同的簽名)

[英]Overriding a method(with the same signature) present in both Parent Class as well as the Interface

我們有一個Class (比如Animal ),我們有一個Interface (比如Behave )。 AnimalBehave都有一個具有相同簽名的方法(比如public void eat() )。

當我們嘗試在extends Animalimplements Behave Behave 的Class (比如Dog )中編寫方法eat()的主體時,實際引用的是哪個eat()方法? AnimalBehave中的那個。 無論哪種情況發生,為什么會這樣發生?

編輯:

在發布此問題之前,我在Eclipse上嘗試過這種情況。

這里一個有趣的部分是,即使我正在實現Behave ,如果我不在Dog中創建一個eat()方法(即,如果我不實現Behave's繼承抽象方法),就沒有錯誤,因為我已經從Animal擴展了一個eat()方法。

which eat() method is actually referred to? 兩個都。

試試這個:如果你根本不覆蓋這個方法,當你用接口調用時,你會從父級那里得到一個。

Behave b = new Dog();
System.out.println(b.eat());//this will call eat from Animal if Dog did not override.

如果你覆蓋,你總是從孩子那里得到一個:

Behavior b = new Dog();
Animal a = new Dog();

a.eat() and b.eat() will both refer to the eat inside of Dog class.

使用這些課程:

public class BClass {
public int add(int a, int b){
    return a*b;
}
}

public interface BInterface {
public int add(int a, int b);
}

public class BChild extends BClass implements BInterface{
public static void main(String... args){
    BInterface bi = new BChild();
    BClass bc = new BChild();
    System.out.println(bi.add(3, 5));
    System.out.println(bi.add(3, 5));
}

@Override
public int add(int a, int b){
    return a+b;
}
}

接口只能包含方法的主體定義,一旦實現,它必須實現所有定義的方法。 在你的例子中

class Dog extends Animal implements Behave
{
    @Override
    public void eat() {...}
 }

 abstract class Animal{
    public abstract void eat();
 }
 interface Behave{
    void eat();
 }

這里它需要一個抽象方法體,就像在 Main 方法中一樣。 換個方式

class DOG extends Animal implements Behave{
    ...
}

class Animal{
   public  void eat(){
        ...
   }
}

interface Behave{
    void eat();
}

這里狗 class 在它的超級 class 動物中有吃法身體。 所以它不會要求在 Animal 中再次實現 body,因為它已經實現了。

接口只是定義了 class 必須提供的方法。 如果我們有

public class Animal{
    public void eat(){
        System.out.println("Om nom nom");
    }
}
public class Dog extends Animal{

}

Dog 現在提供了 eat 方法並且可以實現Behave

只有一個eat()方法,因為該語言的設計者認為讓方法簽名由其名稱和參數類型組成的簡單性比能夠指定您正在提供的實現的復雜性更有用一個界面。

在 Java 中,如果兩者具有不同的語義,請提供一個方法,該方法返回一個執行其他操作的 Behave 實例:

class Animal { 
    public void eat () { }
}

interface Behave { 
    void eat (); 
}

class Dog extends Animal { 
    public void eat () { 
        // override of Animal.eat()
    } 

    public Behave getBehave() { 
        return new Behave { 
            public void eat() { 
                BehaveEat(); 
            } 
        };
    }

    private void BehaveEat() {
        // effectively the implementation Behave.eat()
    }
}

在其他語言中,您可以顯式 state 一個方法實現接口中的一個方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM