【发布时间】:2014-04-12 07:14:50
【问题描述】:
我开始认为我不像我想象的那样理解多态性。
我有以下情况:
public class Testing {
public static void main(String[] args){
interTest myTest = new classTest();
myTest.classMethod();
}
}
使用给定的接口:
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 文档演示了实现一个接口,然后添加其他方法,甚至实现多个接口(因此包括不在其中一个接口中的方法),我认为这是司空见惯的,直到我遇到问题试图自己做。
在这种情况下,我无法访问classMethod,因为它不在界面内。
The method classMethod() is undefined for the type interTest
我对多态性有什么不了解?我想以如下形式声明一个变量:
Interface object = new ConcreteClass();
创建了一个可以访问 ConcreteClass() 方法的接口对象。这就是您制作多个对象的方法,这些对象都具有相同的类型(接口),并且可以放入特定类型的列表中,但它们是不同的。
为什么我不能调用myTest.classMethod() 方法?
【问题讨论】:
标签: java methods interface scope polymorphism