是否可以通过继承和接口在一个类中两次存在相同的方法? [英] Can a same method exist in a class twice, through Inheritance and interfaces?
问题描述
这是场景:-
class Canine{
public void roam(){
System.out.println("Canine-Roam");
}
}
public interface Pet{
public abstract void roam();
}
class Dog extends Canine implements Pet{
public void roam(){
System.out.println("Dog Roam");
}
public static void main(String [] args){
Dog adog = new Dog();
adog.roam();
}
}
我知道JVM在选择运行哪种方法时一定不要有任何困惑,这意味着哪种方法会被覆盖.但是我还是很困惑.为什么要编译该程序?
I am aware that JVM must not have any confusion in choosing which method to run, that means, which method gets over-ridden. But I am confused anyway. Why does this program compile?
推荐答案
否-同一方法不能在一个类中两次存在.
No - the same method cannot exist in a class twice.
接口仅声明用于类的 requirement 即可实现特定方法.它实际上并没有创建该方法.
An interface simply declares a requirement for a class to implement a particular method. It does not actually create that method.
因此,通过继承获取方法实现的类已定义了该方法.此(单个)实现满足接口的要求.
So a class that acquires a method implemention through inheritance has that method defined. This (single) implementation satisfies the interface's requirements.
在您的情况下:
-
Dog
扩展了Canine
,因此这意味着Canine
中的roam()
方法可用,并且如果不被重写,它将作为Dog对象的一种方法公开. - 但是然后
Dog
,然后使用其自己的roam()
定义来覆盖超类方法.这是允许的,并且在Dog
上仍然只有一个明确的方法称为roam()
-新的替代方法. -
Dog
实现Pet
,这意味着需要具有roam()
方法.确实如此-这是该接口的有效实现.
Dog
extendsCanine
, so it means that theroam()
method fromCanine
is available, and would be exposed as a method on Dog objects if not overridden.- But then
Dog
then overrides the superclass' method with its own definition ofroam()
. This is allowed, and there is still just one unambiguous method calledroam()
onDog
- the new override. Dog
implementsPet
, which means it is required to have aroam()
method. It does - so it's a valid implementation of this interface.
这篇关于是否可以通过继承和接口在一个类中两次存在相同的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!