[英]Specify that a method argument must inherit from one class and implement an interface
[英]Can a class inherit implementation of a method contruct imposed by an interface from other class?
我正在查看由其他人编写的旧代码,然后发现有一个类实现了接口,但没有实现接口中声明的所有方法。
当我尝试使用eclipse在接口中查找方法的实现时,我发现了这一点(突出显示该方法并执行ctl + Shit + G =在工作空间中未找到实现)。 仔细研究代码,我发现该方法的实现实际上是从该类扩展的另一个Abstract类继承的。
这是我在说的简单版本:
interface myInterface{
int needsTobeImplemeted(int x);
}
abstract class myAbstractClass{
int needsTobeImplemeted(int x){
return x;
}
}
class myClass extends myAbstractClass implements myInterface
{
}
从主打印中调用该方法=>结果:0
public static void main(String[] args) {
myInterface interfaceType = new myClass();
System.out.println("result: " + interfaceType.needToBeImplemeted(0));
}
我的问题是这怎么可能? 如果myClass覆盖该方法,将会发生什么:
@override
int needsTobeImplemeted(int x){
return x*x;
}
它正在实现哪种方法,接口中的on或Abstract类中的on? 顺便说一下,扩展类不必是抽象类,而可以是普通类。 如果它具有与myInterface中定义的签名相同的方法,就足够了。
任何解释将不胜感激;)
覆盖myClass中的方法:
public class myClass extends myAbstractClass implements myInterface {
@Override
public int needToBeImplemeted(int x)
{
return x*x;
}
}
public static void main(String[] args) {
myClass classType = new myClass();
myAbstractClass abstractType = new myClass();
myInterface interfaceType = new myClass();
System.out.println("result: " + classType.needToBeImplemeted(2));
System.out.println("result: " + abstractType.needToBeImplemeted(2));
System.out.println("result: " + interfaceType.needToBeImplemeted(2));
}
结果:
结果:4
结果:4
结果:4
它正在实现哪种方法,接口中的on或Abstract类中的on?
该类根本没有“实现”方法。 它“实现”一个接口。 实现接口只是意味着“拥有该接口描述的所有方法”。
定义该方法在类或其继承树中的哪个位置都没有关系。 因此,如果要实现在接口或抽象方法中找到的方法,也没有什么不同。 唯一重要的是是否存在具有该签名的方法。
实现接口的非抽象类必须具有所有接口方法的实现。 它是实现这些方法还是从其超类继承实现都没有关系。 如果它覆盖了超类的needsTobeImplemeted
实现,则意味着在needsTobeImplemeted
的实例上调用needsTobeImplemeted
将调用子类的实现。
在您的示例中,无论是否在myClass
子类中覆盖它, interfaceType.needToBeImplemeted(0)
将返回0,因为0 = 0 * 0。
myClass
实现myInterface
,这意味着它必须具有 myInterface
描述的行为 。 myClass
具有此行为,因为它是 myAbstractClass
并继承了它的所有方法 。
回答您的问题:
它正在实现哪种方法,接口中的on或Abstract类中的on?
myClass
本身并未实现该方法,而是从myAbstractClass
继承了该方法以符合myInterface
。
如果您这样说:
@Override
int needsTobeImplemeted(int x){
return x*x;
}
在myClass
内部,您将重写myAbstractClass
的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.