Java-实验12 多态

实验12 多态

一、实验目的

1. 掌握对象转型。

2. 掌握instanceof。

3. 掌握多态的使用。

二、实验内容

1. 多态试验

1创建电器类,

声明电器的属性:功率、额定电压、额定电流、交直流类型,

电器的方法:工作方法。
创建电视机类和冰箱类继承电器类,

电视机类增加属性:种类、最大音量,重写工作方法。

电冰箱类增加属性:容量,重写工作方法。

创建测试类,用多态实现,另外写一个方法,参数为电器类,在方法中根据传入对象的不同分类对其处理,输出其所有属性。。

package mybag;

public class ElecticTest {
  public static void main(String[] args){
	   TV tv=new TV("12W","4V","6A","交流","长虹","34HZ");
           Fridge f=new Fridge("25W","41V","16A","直流","1500L");
           Electic a=tv;
           getPlay(a);
           Electic b=f;
           getPlay(b);
  }
  public static void getPaly(Electic t){
          t.useMethod();
  }
}
class Electic{
	String pow,dianYa,edingDya,jiaoZhiType;
	void useMethod(){}
}
class TV  extends Electic{
	String type,maxVoice;
	TV(String pow,String dianYa,String edingDya,String jiaoZhiType,String type,String maxVoice){
		this.pow=pow;
		this.dianYa=dianYa;
		this.edingDya=edingDya;
		this.jiaoZhiType=jiaoZhiType;
		this.type=type;
		this.maxVoice=maxVoice;
	}
	
	void useMethod(){//重写
		System.out.println("方法:打开电视,收看节目");
		System.out.println("功率:"+pow+" 额定电压:"+dianYa+" 额定电流:"+edingDya+" 交直流类型:"+jiaoZhiType);
		System.out.println("独有属性:\n类型:"+type+"  最大音量:"+maxVoice);
	}
}
class Fridge extends Electic{
	String v;
	Fridge(String pow,String dianYa,String edingDya,String jiaoZhiType,String v){
		this.pow=pow;
		this.dianYa=dianYa;
		this.edingDya=edingDya;
		this.jiaoZhiType=jiaoZhiType;
		this.v=v;
	}
	void useMethod(){
		System.out.println("打开电冰箱,存放物品");
		System.out.println("功率:"+pow+" 额定电压:"+dianYa+" 额定电流:"+edingDya+" 交直流类型:"+jiaoZhiType);
		System.out.println("独有属性:\n容量:"+v);
	}
	
}

java实验

2请编码实现如下需求:

1 )抽象类乐器( Instrument )分为:钢琴 (Piano) 、小提琴 (Violin)
2 )各种乐器的弹奏(  play )方法各不相同。
编写一个测试类 InstrumentTest ,要求:
1 )编写方法 testPlay ,参数为 Instrument, 对各种乐器进行弹奏测试。要依据乐器的不同,进行相应的弹奏。

2)在main方法中进行测试

package mybag;

public class InstrumentTest {
  public static void main(String[] args){
	  Violin p1=new Violin();
	  testPlay(p1);
	  Piano p=new Piano();
	  testPlay(p);
  }
  public static void testPlay(Instrument a){
	  a.play();
  }
}
abstract class Instrument{
	abstract void play();
}
class Violin extends Instrument{
	void play(){
		System.out.println("小提琴的弹奏......");
	}
}
class Piano extends Instrument{
	void play(){
		System.out.println("钢琴的弹奏.....");
	}
	
}
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值