实验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("钢琴的弹奏.....");
}
}