我开始认为我并不像我想象的那样理解多态性。
我有以下情况:
public class Testing {
public static void main(String[] args){
interTest myTest = new classTest();
myTest.classMethod();
}
}
使用给定的接口(interface):
public interface interTest {
public boolean checkBoolean();
public void method();
}
然后是具体类:
public class classTest implements interTest{
public classTest() {
// TODO Auto-generated constructor stub
}
public void classMethod(){
System.out.println("fail");
}
// Both method() and checkBoolean() are overridden here & do nothing.
}
}
Oracle 文档演示了实现一个接口(interface),然后添加其他方法,甚至实现多个接口(interface)(因此包括不在其中一个接口(interface)中的方法),我认为这是很常见的,直到我遇到了尝试解决问题的问题。我自己做这个。
在这种情况下,我无法访问 classMethod
,因为它不在接口(interface)内部。
The method classMethod() is undefined for the type interTest
我对多态性有什么不理解的地方?我想以以下形式声明一个变量:
Interface object = new ConcreteClass();
创建了一个可以访问ConcreteClass()方法的接口(interface)对象。这就是创建多个对象的方法,这些对象都具有相同的类型(接口(interface)),并且可以适合特定于类型的列表,但又不同。
为什么我无法调用 myTest.classMethod()
方法?
最佳答案
在编译时,方法根据调用它们的表达式的类型进行解析。
在
Interface object = new ConcreteClass();
object.classMethod();
方法 classMethod()
在类型为 Interface
的变量上调用,该变量没有声明或没有名为 classMethod()
的可见方法>.
类型ConcreteClass
确实声明了这样一个方法,所以你可以这样做
ConcreteClass object = new ConcreteClass();
object.classMethod();
甚至
((ConcreteClass) object).classMethod();
如果您确定object
正在引用ConcreteClass
对象。否则,您将在运行时收到 ClassCastException
。
基本上,您需要了解编译时类型和静态类型与运行时类型和动态类型之间的区别。
在
Interface object = new ConcreteClass();
object
的静态类型是Interface
。在运行时,该变量引用 ConcreteClass
类型的对象,因此其运行时类型为 ConcreteClass
。
关于java - 无法从实现接口(interface)的类中实现方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278918/