定义普通的基类Building类,有楼房号、层数、房间数及建筑面积属性。定义派生类House类继承Building类,并包含数据成员卧室的数量、卫生间的数量。定义派生类Office 类继承Building类,包含数据成员灭火器数及办公桌数量。
时间: 2024-11-30 20:14:36 浏览: 29
在面向对象编程中,我们可以定义一个基础类型的类作为其他类的模板,这就是我们所说的基类。这里有一个名为`Building`的基类,它包含了通用的建筑物信息,如:
```java
public class Building {
private String buildingNumber;
private int numberOfFloors;
private int roomCount;
private double floorArea;
// 构造函数
public Building(String number, int floors, int rooms, double area) {
this.buildingNumber = number;
this.numberOfFloors = floors;
this.roomCount = rooms;
this.floorArea = area;
}
// 获取和设置属性的方法
// ...
}
```
然后,为了满足特定需求,我们创建两个派生类:`House` 和 `Office`。这两个类都继承自 `Building` 并添加了特有的属性:
```java
class House extends Building {
private int bedroomCount;
private int bathroomCount;
// House的构造函数
public House(String number, int floors, int rooms, double area, int bedrooms, int bathrooms) {
super(number, floors, rooms, area);
this.bedroomCount = bedrooms;
this.bathroomCount = bathrooms;
}
// 获取和设置卧室/卫生间的方法
// ...
}
class Office extends Building {
private int fireExtinguishers;
private int deskCount;
// Office的构造函数
public Office(String number, int floors, int rooms, double area, int extinguishers, int desks) {
super(number, floors, rooms, area);
this.fireExtinguishers = extinguishers;
this.deskCount = desks;
}
// 获取和设置灭火器/办公桌的方法
// ...
}
```
阅读全文