2011-04-23 2 views
0

내 코드는 다음 두 문장의 차이차이는

Sample sam = new Sample(); 
interf int = new Sample(); 
+2

잘못된 이름은 - int입니까? :) –

+0

[Java - 클래스 대신 인터페이스 유형에서 선언] 가능한 복제본 (http://stackoverflow.com/questions/3383726/java-declaring-from-interface-type-instead-of-class) – Louis

답변

0

하나 개의 기준은 당신이에 선언 된 메소드를 호출 할 수 있습니다 무엇입니까

class Sample implements interf { 
    public void intmethod(){ //some code.... } 
} 

public interface interf{ public void intmethod() } 

내 질문은 클래스를 사용하면 인터페이스에서 선언 된 메서드를 호출 할 수 있습니다. 이 아주 간단한 경우, Sample에있는 유일한 메소드가 interf에 정의 된 경우, 아무런 차이가 없어야합니다.

1

Sample sam = new Sample();을 사용하면 Sample 유형의 참조가 있고 Sample 클래스가 정의하는 방식으로 sam과 작업 할 수 있습니다. interf int = new Sample();

, 당신은 유형 Sample의 객체를 가지고 있지만, 당신은 단지 방식으로 작동 할 수 있습니다 예를 들어 interf을 정의 (Sample에 사용할 수 있지만 참조를 캐스팅없이 호출 할 수 없습니다 interf에 선언되지 않은 방법 ~ Sample). 그러나 기본 구현과 관계없이 interf이 예상되는 곳이면 어디서든 사용할 수 있습니다.

두 번째 형식은 일반적으로 모든 코드를 리팩터링하지 않고 나중에 기본 구현을 스왑 할 수 있으므로 선호됩니다.

0
Sample sam = 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() } 

당신은 할 수있을 것입니다 :

2

의 당신이 있다고 가정 해 봅시다

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(); 
} 

오라클 자습서를 인터페이스 및 다형성 페이지 :

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

+0

정말 고맙습니다. 너의 도움 .... 고마워. –

0

인터페이스는 구체적인 클래스에 대한 기반을 제공합니다. 그것은 구현 클래스에 의해 채워 져야하는 계약을 정의합니다. 따라서 다형성이 필요한 경우에 충분히 사용할 수 있습니다. 예를 들어, 당신은 몇 가지 클래스와 인터페이스 같은 경우 : 둘 다 의사에 대한 일반적인 몇 가지 일반적인 작업 (doCheckUp) 당신이 좋아하는 인터페이스를 사용한다을 수행하려는 경우 여기

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 } } 

public void routineChecup(Doctor d){ 
    d.doCheckUp(); 
}  

이 경우 전달하는 객체에 관계없이 해당 객체의 doCheckUp 메소드가 호출됩니다. 그러나 구체적인 클래스에는 몇 가지 추가 메서드가있을 수 있으며 이러한 메서드를 사용하려면 해당 구체적인 클래스 개체를 사용하여 메서드를 호출해야합니다.

그래서 일반적인 일반적인 방법을 사용하려면 인터페이스 인스턴스를 사용해야합니다.