2014-06-18 53 views
-3

你能幫我解決這個代碼嗎?簡單的Java接口實現

interface Speaker { 

    void speak(); 

} 
public class Politician implements Speaker { 

    public void speak() { 
     System.out.println("Politician speaking"); 
    } 
} 
public class Lecturer implements Speaker { 

    public void speak() { 
     System.out.println("Lecturer spaeking"); 
    } 

} 

public class SpeakerTest { 

    public static void main(String[] args) { 

     //??????????????? how to execute? 


    } 
} 
+1

你想做什麼? – BobTheBuilder

+0

這裏的問題很明顯:如何「instanciate」並使用界面:) Upvoting ... – user3001

回答

1
public static void main(String[] args) { 

Speaker s1,s2; 
s1 = new Lecturer(); 
s2 = new Politician(); 

s1.speak(); // it print 'Lecturer spaeking' 
s2.speak(); // it print 'Politician speaking' 

} 
+0

感謝您的快速回復! 我找到了我的答案。 但我必須初始化每個類。我認爲會有一行代碼一次執行所有的方法。 –

0
Speaker s = new AnInstanceOfAClassThatImplementsSpeaker();//instead of //??????????????? how to execute? 
s.speak(); // will call appropriate speak() method` 
0

的接口基本上是一個合同,其方法是對其他類可見。與抽象類相反,內部沒有功能(除了靜態方法)。

接口方法的具體實現是在實現接口的類中完成的。所以這些類必須遵守接口的方法契約。

因此,您在主要方法中聲明瞭Speaker類型的變量並指定了該類的實例(本例中爲PoliticianLecturer)。

public class SpeakerTest { 

    public static void main(String[] args) { 
     // Speaker is the Interface. We know it has a speak() method and do not care about the implementation (i.e. if its a politicial or a lecturer speaking) 
     Speaker firstSpeaker = new Politician(); 
     firstSpeaker.speak(); 
     Speaker secondSpeaker = new Lecturer(); 
     secondSpeaker.speak(); 

    } 
} 
+0

這是我的另一個問題。如果有這麼多的實施類,我必須發起每一堂課。有沒有辦法讓它成爲單行代碼?那可能嗎?任何其他算法?提前致謝。 –