类引用和接口引用之间的区别

时间:2011-04-23 16:23:56

标签: 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();

5 个答案:

答案 0 :(得分:2)

假设你有:

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教程页面:

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

答案 1 :(得分:1)

使用Sample sam = new Sample();,您的引用类型为Sample,您可以sam类定义的方式使用Sample

使用interf int = new Sample();,虽然您有Sample类型的对象,但您只能以interf定义的方式工作(例如,{{1}中可用的方法如果没有强制引用Sample,则无法在interf中声明但未声明。但是,无论底层实现如何,您都可以在预期Sample的任何地方使用它。

第二种形式通常是首选,因为您可以在以后更换底层实现,而不必担心重构所有代码。

查看有关使用接口与实现类的更多讨论:

答案 2 :(得分:0)

一个引用将允许您调用类中声明的方法,另一个允许您调用接口中声明的方法。在这个非常简单的情况下,Sample中的唯一方法是interf中定义的方法,它不会对您产生任何影响。

答案 3 :(得分:0)

Sample sam = new Sample(); 

允许访问Sample类的所有方法。

interf int = new Sample();  

只允许访问接口所具有的那些方法。

答案 4 :(得分:0)

Interface为具体类提供了基础。它定义了必须由实现类完全填充的合同。因此,如果您需要多态性,它可以使用完整。例如,如果你有一些类和接口,如:

interface Doctor{   void doCheckUp();   }  

class HumanDoctor implements doctor{  

public void doCheckUp(){  
    //checkup code here   }

public doHumanRelatedStuff(){   // Human Related Stuff   }  
   }  

class AnimalDoctor implements doctor{   public void doCheckUp(){   //checkup code here   }  

public doAnimalRelatedStuff(){   // Animal Related Stuff   }   }

如果你想做一些医生(doCheckUp)常见的通用工作,你应该使用像

这样的界面
 public void routineChecup(Doctor d){  
     d.doCheckUp();  
 }    

在这种情况下,无论您传递哪个对象,都会调用相应对象的doCheckUp方法。 但是你的具体类可以有一些额外的方法,如果你想使用那些方法,那么你必须使用相应的具体类对象来调用方法。

因此,如果要使用通用公共方法,则应使用接口实例。

相关问题