我们有一个Class(比如Animal),我们有一个接口(比如Behave). Animal和Behave都有一个具有相同签名的方法(比如public void eat()).
当我们尝试在一个类(比如Dog)中编写方法eat()时,它扩展了Animal并实现了Behave,其中eat()方法实际上是指?动物或行为中的那个.无论发生哪种情况,为什么会这样?
编辑:
在发布此问题之前,我在Eclipse上尝试了这个场景.
这里有一个有趣的部分是,即使我正在实现Behave,如果我不在Dog内创建一个eat()方法(即如果我不实现Behave的继承抽象方法),那么就没有错误,因为我已经从Animal扩展了一种eat()方法.
解决方法:
哪个eat()方法实际上是指?都.
试试这个:如果你根本没有覆盖这个方法,当你用界面调用时,你将从父进程中获取一个.
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;
}
}
标签:java,override
来源: https://codeday.me/bug/20190630/1334195.html