Java的多态——看程序时自动带感

本文通过具体实例演示了Java中如何实现多个接口,并展示了接口方法的使用。学生类实现了Singer接口,教师类同时实现了Singer和Painter接口。文章还探讨了多态性和对象转型的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值