第八次实验报告.
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
第八次实验
实验1:中国人、北京人和美国人
1.实验要求:
编写程序模拟中国人、美国人是人,北京人是中国人。除主类外,程序中还有4个类:People、ChinaPeople、AmericanPeople和BeijingPeople 类。要求如下:
(1)People类有权限是protected的double型成员变量height和weight,以及public void speakHello()、public void averageHeight()和public void averageWeight()方法。
(2)ChinaPeople类是People的子类,新增了public void averageHeight()和public voidaverageWeight()方法。
(3)AmericanPeople类是People的子类,新增方法public void AmericanBoxing()。
要求AmericanPeople重写父类的public void speakHello()、public void averageHeight()和public void averageWeight()方法。
(4)BeijingPeople类是ChinaPeople的子类,新增public void beijingOpera()方法。
2.实验代码:
//People.java
public class People {
protected double weight,height;
public void speakHello() {
System.out.println("yayayaya");
}
public void averageHeight() {
height=173;
System.out.println("average height:"+height);
}
public void averageWeight() {
weight=70;
System.out.println("average weight:"+weight);
}
}
//ChinaPeople.java
public class ChinaPeople extends People {
public void speakHello() {
System.out.println("您好");
}
public void averageHeight() {
height=168.78;
System.out.println("中国人的平均身高:"+height+"厘米");
}
public void averageWeight() {
weight=65;
System.out.println("中国人的平均体重:"+weight+"千克");
}
public void chinaGongfu() {
System.out.println("坐如钟,站如松,睡如弓");
}
}
//AmericanPeople.java
public class AmericanPeople extends People {
public void speakHello () {
System.out.println("How do you do");
}
public void averageHeight() {
height=176;
System.out.println("American's average height:"+height+"厘米");
}
public void averageWeight() {
weight=75;
System.out.println("American's average weight:"+weight+" kg");
}
public void americanBoxing() {
System.out.println("直拳,勾拳,组合拳");
}
}
//BeijingPeople.java
public class BeijingPeople extends ChinaPeople {
public void averageHeight() {
height=172.5;
System.out.println("北京人的平均身高:"+height+"厘米");
}
public void averageWeight() {
weight=70;
System.out.println("北京人得平均体重:"+weight+"千克");
}
public void beijingOpera() {
System.out.println("花脸、青衣、花旦和老生");
}
}
//Example.java
public class Example {
public static void main(String arg[]) {
ChinaPeople chinaPeople=new ChinaPeople();
AmericanPeople americanPeople=new AmericanPeople();
BeijingPeople beijingPeople=new BeijingPeople();
chinaPeople.speakHello();
americanPeople.speakHello();
beijingPeople.speakHello();
chinaPeople.averageHeight();
americanPeople.averageHeight();
beijingPeople.averageHeight();
chinaPeople.averageWeight();
americanPeople.averageWeight();
beijingPeople.averageWeight();
chinaPeople.chinaGongfu();
americanPeople.americanBoxing();
beijingPeople.beijingOpera();
beijingPeople.chinaGongfu();
}
}
3.实验结果:
4.实验分析:
(1)方法重写时要保证方法的名字、类型、参数的个数和类型同父类的某个方法完全想同。
这样,子类继承的方法才能被隐藏。
(2)子类在重写方法时,如果重写的方法是static方法,static关键字必须保留;如果重写的
方法是实例方法,重写时不可以用static修饰。