编写程序模拟,除主类外,程序中还有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 chinaGongfu()方法,重写了父类的public void speakHello()、public void averageHeight()和public void averageWeight ()方法。 (3)AmericanPeople类是People类的子类,新增public void americanBoxing()方法,重写父类的public void speakHello()、public void averageHeight()和public void averageWeight ()方法。 (2)BeijingPeople类是ChinaPeople类的子类,新增public void beijingOpera()方法,重写父类的public void speakHello()、public void averageHeight()和public void averageWeight ()方法。
时间: 2024-03-21 13:43:36 浏览: 71
怎样写模拟器程序
3星 · 编辑精心推荐
好的,这是一个面向对象的继承和重写的例子,以下是Java代码示例:
```java
public class People {
protected double height;
protected double weight;
public void speakHello() {
System.out.println("Hello!");
}
public void averageHeight() {
System.out.println("The average height is " + height + " cm.");
}
public void averageWeight() {
System.out.println("The average weight is " + weight + " kg.");
}
}
public class ChinaPeople extends People {
public void chinaGongfu() {
System.out.println("I can do China Gongfu.");
}
public void speakHello() {
System.out.println("Nihao!");
}
public void averageHeight() {
height = 166.3;
super.averageHeight();
}
public void averageWeight() {
weight = 65.4;
super.averageWeight();
}
}
public class AmericanPeople extends People {
public void americanBoxing() {
System.out.println("I can do American Boxing.");
}
public void speakHello() {
System.out.println("Hello!");
}
public void averageHeight() {
height = 175.3;
super.averageHeight();
}
public void averageWeight() {
weight = 75.6;
super.averageWeight();
}
}
public class BeijingPeople extends ChinaPeople {
public void beijingOpera() {
System.out.println("I can do Beijing Opera.");
}
public void speakHello() {
System.out.println("Nihao, I am from Beijing.");
}
public void averageHeight() {
height = 173.5;
super.averageHeight();
}
public void averageWeight() {
weight = 68.2;
super.averageWeight();
}
}
public class Main {
public static void main(String[] args) {
People p = new People();
ChinaPeople c = new ChinaPeople();
AmericanPeople a = new AmericanPeople();
BeijingPeople b = new BeijingPeople();
p.speakHello();
p.averageHeight();
p.averageWeight();
c.speakHello();
c.averageHeight();
c.averageWeight();
c.chinaGongfu();
a.speakHello();
a.averageHeight();
a.averageWeight();
a.americanBoxing();
b.speakHello();
b.averageHeight();
b.averageWeight();
b.chinaGongfu();
b.beijingOpera();
}
}
```
在这个例子中,People类是父类,ChinaPeople和AmericanPeople类是它的子类。BeijingPeople类是ChinaPeople类的子类。每个子类都重写了父类的方法,同时也新增了自己的方法。在Main类中,我们可以创建不同的对象并调用它们的方法,来演示继承和重写的效果。
阅读全文