创建一个Boat(船)类,它有四个属性:registrationNo(注册 号)、length(长)、manufacturer(制造商)、year(年), 方法toString返回所有属性的值。 SailBoat(帆船)类和PowerBoat(汽艇)类继承Boat类, SailBoat类还有keelDepth(龙骨深度)和id(帆船编号)属性, PowerBoat还有numberEgines(引擎数)和fuelType(燃料类 型)属性。在SailBoat类和PowerBoat类重写toString方法(要 求调用父类方法)。 分别创建三个类的对象,使用setter或构造方法赋值,输出其所 有属性值。java
时间: 2023-07-15 07:12:09 浏览: 130
以下是 Boat 类的实现:
```java
public class Boat {
private String registrationNo;
private double length;
private String manufacturer;
private int year;
public Boat(String registrationNo, double length, String manufacturer, int year) {
this.registrationNo = registrationNo;
this.length = length;
this.manufacturer = manufacturer;
this.year = year;
}
public String toString() {
return "Registration No: " + registrationNo + "\nLength: " + length + "\nManufacturer: " + manufacturer + "\nYear: " + year;
}
}
```
以下是 SailBoat 类的实现:
```java
public class SailBoat extends Boat {
private double keelDepth;
private int id;
public SailBoat(String registrationNo, double length, String manufacturer, int year, double keelDepth, int id) {
super(registrationNo, length, manufacturer, year);
this.keelDepth = keelDepth;
this.id = id;
}
public String toString() {
return super.toString() + "\nKeel Depth: " + keelDepth + "\nID: " + id;
}
}
```
以下是 PowerBoat 类的实现:
```java
public class PowerBoat extends Boat {
private int numberEngines;
private String fuelType;
public PowerBoat(String registrationNo, double length, String manufacturer, int year, int numberEngines, String fuelType) {
super(registrationNo, length, manufacturer, year);
this.numberEngines = numberEngines;
this.fuelType = fuelType;
}
public String toString() {
return super.toString() + "\nNumber of Engines: " + numberEngines + "\nFuel Type: " + fuelType;
}
}
```
以下是测试代码:
```java
public class BoatTest {
public static void main(String[] args) {
Boat boat = new Boat("A1234", 10.5, "Boat Company", 2022);
System.out.println(boat);
SailBoat sailBoat = new SailBoat("B5678", 15.0, "Sailboat Company", 2022, 3.0, 1);
System.out.println(sailBoat);
PowerBoat powerBoat = new PowerBoat("C9101", 20.0, "Powerboat Company", 2022, 2, "Gasoline");
System.out.println(powerBoat);
}
}
```
输出结果如下:
```
Registration No: A1234
Length: 10.5
Manufacturer: Boat Company
Year: 2022
Registration No: B5678
Length: 15.0
Manufacturer: Sailboat Company
Year: 2022
Keel Depth: 3.0
ID: 1
Registration No: C9101
Length: 20.0
Manufacturer: Powerboat Company
Year: 2022
Number of Engines: 2
Fuel Type: Gasoline
```
阅读全文