[英]JAVA :access method defined in class , but not implemented by its interface
Interface: 接口:
public interface InterfaceA {
public void PartOfIinterfaceA();
}
Class: 类:
public class Class_To_Test_Interface_encapsulation implements InterfaceA {
public void MethodM() {
}
@Override
public void PartOfIinterfaceA() {
// TODO Auto-generated method stub
}
}
Main class: 主班:
public class MainClass {
public static void main(String args[]) {
InterfaceA Ia = new Class_To_Test_Interface_encapsulation();
Ia.MethodM();
}
}
Its giving me following error : The method MethodM() is undefined for in type InterfaceA() I very well know, why its giving me error and its logical. 它给了我以下错误:我很清楚方法MethodM()在类型InterfaceA()中是未定义的,为什么它给我错误和逻辑。 Also, I refrred , // Use methods declared in implementation that are not defined in interface
另外,我刷新了,// 使用在实现中声明的未在接口中定义的方法
But, my question is, is there any other way we can , where a piece of code referring to an instance of B (with type InterfaceA) can in fact access m ? 但是,我的问题是,还有其他方法可以使用,其中引用B实例(类型为InterfaceA)的一段代码实际上可以访问m?
It doesn't make sense to access m on an object (InterfaceA) that doesn't have m (the method is not defined in the interface). 在没有m的对象(InterfaceA)上访问m没有意义(该方法未在接口中定义)。 If you know that a subset of InterfaceA will have m defined, you need to determine membership in that subset before accessing m:
如果您知道InterfaceA的一个子集将定义m,则需要在访问m之前确定该子集的成员资格:
if (Ia instanceof Class_To_Test_interface_encapsulation) {
((Class_To_Test_interface_encapsulation)Ia).MethodM();
}
InterfaceA Ia = new Class_To_Test_Interface_encapsulation().MethodM(); InterfaceA Ia =新的Class_To_Test_Interface_encapsulation()。MethodM();
This will skip compile time error, and resolve at runtime correctly and call the method MethodM() 这将跳过编译时错误,并在运行时正确解析并调用方法MethodM()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.