简单的Java接口实现

时间:2014-06-18 13:57:15

标签: java interface

您能帮我解决一下这段代码吗?

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?


    }
}

3 个答案:

答案 0 :(得分: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'

}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

接口基本上是一个合约,其他类可以看到这些方法。与抽象类相反,内部没有任何功能(静态方法除外)。

接口方法的具体实现是在实现接口的类中完成的。所以类必须保持接口的方法契约。

因此,您在main方法中声明类型为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();

    }
}