接口中多态的应用

下面的代码意思是,定义了一个USB接口,这个接口实现了Mouse和Key两个类。在PC类的构造方法中调用这个接口实现的对象,如果接口实现了哪个类,就将这个接口实现的对象向下转型,进入到那个类中,执行那个类中的操作。

class PC{
	void use(USB u){//USB u = new Mouse();/USB u = new Key();
		u.open();
		if(u instanceof Mouse)
		{
			Mouse m=(Mouse)u;
			m.click();
		}
		if(u instanceof Key)
		{
			Key k= (Key)u;
			k.print();
		}
		u.close();		
	}
}

interface USB{//接口
	void open();
	void close();
}

class Mouse implements USB{
	public void open(){
		System.out.println("插上鼠标");
	}
	public void close(){
		System.out.println("拔下鼠标");		
	}

	void click(){
		System.out.println("点击");
	}
}

class Key implements USB{
	public void open(){
		System.out.println("插上键盘");
	}
	public void close(){
		System.out.println("拔下键盘");		
	}

	void print(){
		System.out.println("打字");
	}
}

class DuoTaiDemo3{
	public static void main(String[] args){
		PC pc = new PC();
		pc.use(new Mouse());
		pc.use(new Key());		
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hudie.

不要打赏!不要打赏!不要打赏!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值