interface Singer { public void sing(); public void sleep(); } interface Painter { public void paint(); public void eat(); } class Student implements Singer { private String name; Student(String name) { this.name = name; } public void sing() { System.out.println("Student is singing !"); } public void sleep() { System.out.println("Student is sleeping !"); } } class Teacher implements Singer, Painter { private String name; Teacher(String name) { this.name = name; } public void sing() { System.out.println("Teacher is singing !"); } public void sleep() { System.out.println("Teacher is sleeping !"); } public void paint() { System.out.println("Teacher is painting !"); } public void eat() { System.out.println("Teacher is eatting !"); } } public class Interface { public static void main(String[] args) { Singer s1 = new Student("S"); s1.sing(); s1.sleep(); Singer s2 = new Teacher("T"); s2.sing(); s2.sleep(); Painter s3 = (Painter) s2; s3.paint(); s3.eat(); } }
Interface.java
本文通过具体的Java代码示例介绍了如何实现接口以及多态的概念。定义了Singer和Painter两个接口,并通过Student和Teacher类实现了这些接口,展示了如何在不同类中复用相同的方法签名来实现多态行为。

被折叠的 条评论
为什么被折叠?



