假设我们在java中有一个如下的接口(interface)
public interface AnInterface
{
public void aMethod();
}
和一个类如下:
public class AClass
{
public void aMethod()
{
//bla bla bla
}
}
现在我要定义另一个类,例如扩展 AClass 并实现 AnInterface 的 Subclass,如下所示:
public class Subclass extends AClass implements AnInterface
{
public void aMethod()
{
//do something
}
}
aMethod() 在子类中到底做了什么?它实现了AnInterface中的方法吗?或者它是否重写了AClass中的方法?
为了让aMethod()实现AnInterface的方法,我应该怎么做? 同样,如果我想让它重写AClass中的方法,我该怎么办?
最佳答案
您可能已经注意到,接口(interface)方法没有任何主体。这仅仅意味着,实现此接口(interface)的类必须实现这些方法,此处为aMethod()
。您的类 SubClass
扩展了 AClass
并从中继承了方法 aMethod()
。现在,在 SubClass
中实现 aMethod
将简单地覆盖 AClass
中的方法,同时遵守接口(interface)规则。因此,有效的方法将是子类
中的方法。
简单回答一下你的问题:
子类中的 aMethod()
当前既实现了 AnInterface
中的方法,又重写了 AClass
中的方法。
关于java - java中同名的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33946528/