我的代码是:
class Sample implements interf {
public void intmethod(){ //some code.... }
}
public interface interf{ public void intmethod() }
我的问题是以下两个语句有什么区别
Sample sam = new Sample();
interf int = new Sample();
最佳答案
假设您有:
class Sample implements interf {
public void intmethod(){ //some code.... }
public void sampleMethod() { // code only relevant to Sample objects}
}
class Sample2 implements interf {
public void intmethod(){ //some code.... }
public void sample2Method() { // code only relevant to Sample2 objects }
}
public interface interf{ public void intmethod() }
你将能够做到:
Sample sam = new Sample();
interf intObj = new Sample();
Sample2 sam2 = new Sample2();
sam.intmethod();
sam.sampleMethod();
intObj.intmethod();
// the las one will give you an erro because sampleMethod is not defined for interf
//intObj.sampleMethod()
sam.intmethod();
sam2.sampleMethod2();
但定义 interf 对象将允许您执行此操作:
List<interf> myList = new ArrayList<interf>();
myList.add(sam);
myList.add(intObj);
myList.add(sam2);
for (obj : myList) {
obj.intmethod();
}
Oracle 接口(interface)和多态性教程页面:
http://download.oracle.com/javase/tutorial/java/concepts/interface.html
http://download.oracle.com/javase/tutorial/java/IandI/polymorphism.html
维基百科有一些不止一种语言的有趣示例:
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
关于java - 类引用和接口(interface)引用之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765390/