lei*_*ero 0 java methods polymorphism scope interface
我开始认为我不像我想的那样理解多态性.
我有以下情况:
public class Testing {
public static void main(String[] args){
interTest myTest = new classTest();
myTest.classMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
使用给定的界面:
public interface interTest {
public boolean checkBoolean();
public void method();
}
Run Code Online (Sandbox Code Playgroud)
然后是具体的课程:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
Oracle文档演示了如何实现接口然后添加其他方法,甚至实现多个接口(因此包括不在其中一个接口中的方法),我认为这很常见,直到我遇到试图自己尝试这样做的问题.
在这种情况下,我无法访问,classMethod因为它不在界面内.
The method classMethod() is undefined for the type interTest
Run Code Online (Sandbox Code Playgroud)
我对多态性的理解是什么?我想在表单中声明一个变量:
Interface object = new ConcreteClass();
Run Code Online (Sandbox Code Playgroud)
创建了一个可以访问ConcreteClass()方法的接口对象.这就是如何创建多个对象,这些对象都是相同的类型(接口),并且可以适合特定于类型的列表但是不同.
为什么我不能调用这个myTest.classMethod()方法?
在编译时,方法根据调用它们的表达式的类型来解析.
在
Interface object = new ConcreteClass();
object.classMethod();
Run Code Online (Sandbox Code Playgroud)
在未声明或具有可见方法classMethod()的类型的变量上调用Interface该方法classMethod().
该类型ConcreteClass确实声明了这样的方法,所以你可以这样做
ConcreteClass object = new ConcreteClass();
object.classMethod();
Run Code Online (Sandbox Code Playgroud)
甚至
((ConcreteClass) object).classMethod();
Run Code Online (Sandbox Code Playgroud)
如果你确定object是引用一个ConcreteClass对象.否则你会得到一个ClassCastException运行时间.
基本上,您需要了解编译时类型和静态类型与运行时类型和动态类型之间的区别.
在
Interface object = new ConcreteClass();
Run Code Online (Sandbox Code Playgroud)
静态类型object是Interface.在运行时,变量引用类型的对象ConcreteClass,因此其运行时类型为ConcreteClass.