编写一个Java应用程序,除了主类外,该程序中还有4个类:People、ChinaPeople、AmericanPeople和BeijingPeople。要求如下: People类有访问权限是protected的double型成员变量:height和weight,以及public void speakHello()、public void averageHeight()、public void averageWeight()方法。
时间: 2024-02-18 12:00:52 浏览: 115
好的,下面是一个符合要求的Java应用程序的实现。其中,`People`类是父类,`ChinaPeople`、`AmericanPeople`和`BeijingPeople`类都是子类,继承了`People`类的属性和方法。
People类的实现:
```
public class People {
protected double height;
protected double weight;
public void speakHello() {
System.out.println("Hello, I am a people.");
}
public void averageHeight() {
System.out.println("The average height of people is 1.75 meters.");
}
public void averageWeight() {
System.out.println("The average weight of people is 70 kilograms.");
}
}
```
ChinaPeople类的实现:
```
public class ChinaPeople extends People {
public ChinaPeople(double height, double weight) {
this.height = height;
this.weight = weight;
}
public void speakHello() {
System.out.println("你好,我是中国人。");
}
public void averageHeight() {
System.out.println("中国人的平均身高为:1.68米。");
}
public void averageWeight() {
System.out.println("中国人的平均体重为:65公斤。");
}
}
```
AmericanPeople类的实现:
```
public class AmericanPeople extends People {
public AmericanPeople(double height, double weight) {
this.height = height;
this.weight = weight;
}
public void speakHello() {
System.out.println("Hello, I am an American.");
}
public void averageHeight() {
System.out.println("The average height of American people is 1.78 meters.");
}
public void averageWeight() {
System.out.println("The average weight of American people is 80 kilograms.");
}
}
```
BeijingPeople类的实现:
```
public class BeijingPeople extends ChinaPeople {
public BeijingPeople(double height, double weight) {
super(height, weight);
}
public void speakHello() {
System.out.println("你好,我是北京人。");
}
public void averageHeight() {
System.out.println("北京人的平均身高为:1.72米。");
}
public void averageWeight() {
System.out.println("北京人的平均体重为:70公斤。");
}
}
```
Main类的实现:
```
public class Main {
public static void main(String[] args) {
People people = new People();
people.speakHello();
people.averageHeight();
people.averageWeight();
ChinaPeople chinaPeople = new ChinaPeople(1.70, 60);
chinaPeople.speakHello();
chinaPeople.averageHeight();
chinaPeople.averageWeight();
AmericanPeople americanPeople = new AmericanPeople(1.80, 70);
americanPeople.speakHello();
americanPeople.averageHeight();
americanPeople.averageWeight();
BeijingPeople beijingPeople = new BeijingPeople(1.75, 65);
beijingPeople.speakHello();
beijingPeople.averageHeight();
beijingPeople.averageWeight();
}
}
```
在这个例子中,我们定义了四个类,分别是`People`、`ChinaPeople`、`AmericanPeople`和`BeijingPeople`。`People`类是父类,包含了共有的属性和方法。`ChinaPeople`、`AmericanPeople`和`BeijingPeople`类都继承了`People`类,并重写了其中的方法。
在`Main`类中,我们创建了四个对象,分别是`People`、`ChinaPeople`、`AmericanPeople`和`BeijingPeople`,并调用它们的方法。需要注意的是,由于`ChinaPeople`和`AmericanPeople`都是`People`类的子类,因此它们也可以直接调用`People`类中的方法。而`BeijingPeople`类继承了`ChinaPeople`类,因此它可以调用`ChinaPeople`类和`People`类中的方法。
阅读全文