<pre name="code" class="java">interface Singer{
void sing();
void sleep();
}
interface Painter{
void paint();
void eat();
}
class Student implements Singer{
String name;
Student(String name){
this.name = name;
System.out.print("Sdudent: My name is " + name + ". ");
}
public void run(){
System.out.print("Sdudent: I run fast.");
}
public void sing(){
System.out.print("Sdudent: I can sing a song. ");
}
public void sleep(){
System.out.println("Sdudent: I need keep sleep 8 hours.");
}
}
class Teacher implements Singer, Painter{
String name;
Teacher(String name){
this.name = name;
System.out.print("Teacher: My jobtitle is " + name + ". ");
}
public void sing(){
System.out.print("Teacher: I teach the students sing lots of song. ");
}
public void sleep(){
System.out.print("Teacher: So tired, within 5 hours to have sleep.");
}
public void paint(){
System.out.print("Teacher: I used to enjoy painting... ");
}
public void eat(){
System.out.print("Teacher: I can't have dinner in time.");
}
}
public class TestInterface {
public static void main(String[] args) {
System.out.println("派生类全功能测试");
Student lily = new Student("Lily");
lily.run();
lily.sing();
lily.sleep();
System.out.println("--------------------");
Teacher wang = new Teacher("Staff");
wang.sing();
wang.sleep();
wang.paint();
wang.eat();
System.out.println("\n__________________");
System.out.println("测试:声明接口,new派生。对象只有接口的功能");
Singer tony = new Student("Tony");
tony.sing();
tony.sleep();
//tony.run();//编译器提示,run方法未在Singer类定义
Painter robin = new Teacher("Robin");
robin.paint();
robin.eat();
//robin.sing();//IDE提示没有定义
System.out.println("\n__________________");
Singer connie = (Teacher)robin;
System.out.println("\nNew Singer as connie, she convert to Teacher as robin");
connie.sing();
connie.sleep();
}
}
Java的多态——看程序时自动带感
最新推荐文章于 2025-05-09 18:22:39 发布