2013-07-05 3 views
1

다음 예제에서는 클래스 생성자에서 매개 변수로 전달 될 때 인터페이스 메서드를 직접 호출 할 수있는 이유를 설명 할 수 있습니까? Java 언어 스펙에서 규칙을 검색하려고하지만 찾을 수 없습니다.클래스에서 호출 된 인터페이스 메서드

public interface Interface { 
    public void foo(); 
} 

public class Main { 
    public Main() {} 
    public Main(Interface obj) {obj.foo();} 
    public static int test() {return 123;} 
} 
+0

왜 호출 할 수 없습니까? –

+0

Inteface obj는 참조 변수 일뿐입니다. 구체적인 구현을 참조하고 있습니다. 그래서 당신이 혼란 스럽습니다. – nachokk

답변

3

Java는 그 인터페이스의 메소드 구현을 기대합니다. 즉, 해당 메서드를 구현하는 모든 클래스는 Interface이므로 많은 다른 구현 방법을 사용할 수 있습니다. 의가 있다고 가정 해 봅시다 :

public class ImplementedInterface implements Interface 
{ 
    public void foo() 
    { 
     System.out.println("Hey!, i'm implemented!!"); 
    } 
} 

을 그래서 당신이 호출 할 때 :

Interface aux = new ImplementedInterface(); 
Main m = new Main(aux); 

텍스트를 "야! 내가 구현하고있어!" 인쇄됩니다.

0

여기에 Programming to an interface, not an implementation이 등장합니다. 귀하의 방법은 클래스를 구현하는 클래스의 객체를 기대합니다. interface

예를 들어 설명해 드리겠습니다.

public void deleteFirst(List aList) { 
    System.out.println(aList.remove(0)); 
} 

는 이제 deleteFirst 방법 llal 모두를 전달할 수 있습니다 - 지금은 방법이

우리는 내가 LinkedList<String> ll = new LinkedList<String>();

있다고 가정 해 봅시다 나는 ArrayList<String> al = new ArrayList<String>();

있습니다. 즉, 메서드가 interface을 구현하는 클래스의 개체를 전달한다는 의미입니다.

예에서 ArrayListLinkedList은 모두 List 인터페이스를 구현하므로이 메서드에 전달할 수 있습니다. 궁극적으로 얻는 방법은 List 인터페이스를 구현하는 클래스의 객체입니다.

+0

이것은 전혀 대답하지 않습니다 ... –

+0

답변을 게시하기 전에 기다려야합니다. 유용 할 때까지 게시하지 마십시오. 나는 아직도 그것이 실제로 질문에 대답한다고 생각하지 않는다. –

+0

@JonSkeet - 지금은 이해가 되니? – JHS

1

Interface를 구현하는 클래스의 객체를 저장할 수 있기 때문에 당신은 Interface 참조에서 foo 메소드를 호출 할 수 있으므로 foo 방법을 위해 몸을 제공 할 것입니다.

늦게 바인딩 덕분에 Java는 필요할 때 객체 클래스 코드를 사용합니다.

+0

나는 포인터가 포인터와 같다는 대신에 참조하는 것이 더 적합하다고 생각한다. 참조 xD – nachokk

1

난 당신이 혼란 생각, 당신은 그것이 Interface의 구체적인 구현에서 개체 인 인터페이스

public Main(Interface obj) { 
    obj.foo(); 
} 

OBJ에게의 인터페이스 타입의 cuase 생각합니다.

당신은 예를 들어 Strategy Pattern

으로이 방법을 몇 가지 일반적인 디자인 패턴을 표시 할 수 있습니다

: 대신 구체적인 구현의 추상적 인 계약에 의해 인도의 주요 장점입니다

public interface Searcher { 
    void search(String text, List<String> words); 
} 

public class BinarySearcher implements Searcher{ 
    @Override 
    public void search(String text , List<String> words){ 
     //code here 
    } 

} 

public class LinearSearcher implements Searcher{ 
    @Override 
    public void search(String text ,List<String> words){ 
      // code here 
    } 
} 

public class WordContext { 

private Searcher searcher; 
private List<String> words; 

public void makeSearch(String text){ 
    searcher.search(); // you only know at runtime what subtype will be searcher 
} 

// here you inject by contract 
public void setSearcher(Searcher searcher){ 
    this.searcher= searcher; 
} 

// here you inject by contract 
public void setWords(List<String> words){ 
    this.words = words; 
} 

} 

합니다. 이 예제에서는 주사기를 주사기로 변경할 수 있으며, linearSearcher 또는 binarySearcher가 될 수 있습니다. 즉, 다형성 마법입니다.

관련 문제