简单Java接口实现

简单Java接口实现,java,interface,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(

你能帮我解这个密码吗

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?


    }
}

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

接口方法的具体实现在实现接口的类中完成。因此类必须遵守接口的方法契约

因此,在main方法中声明一个Speaker类型的变量,并在本例中指定类political或讲师的实例

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

    }
}

你想做什么?这里的问题很明显:如何实例化和使用界面:Upvoting…谢谢你的快速回复!我找到了答案。但是我必须初始化每个类。我认为会有一行代码一次执行所有的方法。如果有很多这样的实现类,我必须初始化每个类。有没有办法把它变成单行代码?可能吗?还有其他算法吗?提前谢谢。
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'

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

    }
}