我们有一个Class
(比如Animal
),我们有一个Interface
(比如Behave
)。Animal
和Behave
都有一个具有相同签名的方法(例如public void eat()
)。
当我们尝试在Class
(比如Dog
)中编写方法的主体eat()
哪个extends Animal
和implements Behave
,实际上指的是哪个eat()
方法?Animal
或Behave
的那个.无论哪种情况发生,为什么会这样?
编辑:
在发布此问题之前,我在Eclipse
上尝试了这种情况。
这里一个有趣的部分是,即使我正在实现Behave
,如果我没有在Dog
内创建一个eat()
方法(即如果我不实现继承Behave's
抽象方法),则没有错误,因为我已经从具有eat()
方法Animal
扩展。
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();
}
这里狗类有吃方法身体在其超级类动物。因此,它要求在动物中再次实现身体,因为它已经实现。
接口只是定义类必须提供的方法。如果我们有
public class Animal{
public void eat(){
System.out.println("Om nom nom");
}
}
public class Dog extends Animal{
}
狗现在提供了吃方法,可以这样实现Behave
。
eat()
,因为语言的设计者认为,让方法签名由其名称和参数类型组成比具有能够指定提供接口实现的复杂性更有用。
在 Java 中,如果两者具有不同的语义,请提供一个返回 Beact 实例的方法,该实例执行其他操作:
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()
}
}
在其他语言中,可以显式声明方法从接口实现方法。