java - 类引用和接口(interface)引用之间的区别

标签 java class interface

我的代码是:

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/

相关文章:

.net - 接口(interface)中的可选方法

java - 鼠标事件 JavaFx 上未显示标签

Java OOP 公共(public)、私有(private)、 protected

c++ - 具有相同名称的类 - 是否仅限于同一翻译单元?

c# - 如何使用反射获取特定接口(interface)类型的所有字段

java - 为什么我没有使用 Android 中的界面从之前的 Activity 中获取其他 Activity 中的数据

java - 指定 URLConnection 响应的文档编码

java - 如何在 JPA 中获得独特的结果

java - 如何将十六进制值写入二进制文件

c++ - 在类中创建类的实例时,构造函数参数放在哪里?