用Java写设计Flight类。 要求: (1)具有机型、班次、额定载客数和实际载客数等属性; (2)具有输入/输出属性功能; (3)求载客率; (4)重载toString方法,用于对象属性值的输出。
时间: 2024-01-23 11:03:46 浏览: 113
好的,这是一个简单的Flight类的Java代码示例:
```java
public class Flight {
private String model; // 机型
private String flightNumber; // 班次
private int capacity; // 额定载客数
private int passengers; // 实际载客数
// 构造方法
public Flight(String model, String flightNumber, int capacity, int passengers) {
this.model = model;
this.flightNumber = flightNumber;
this.capacity = capacity;
this.passengers = passengers;
}
// 输入属性
public void setModel(String model) {
this.model = model;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public void setPassengers(int passengers) {
this.passengers = passengers;
}
// 输出属性
public String getModel() {
return model;
}
public String getFlightNumber() {
return flightNumber;
}
public int getCapacity() {
return capacity;
}
public int getPassengers() {
return passengers;
}
// 求载客率
public double loadFactor() {
return (double) passengers / capacity;
}
// 重载toString方法
@Override
public String toString() {
return "Flight{" +
"model='" + model + '\'' +
", flightNumber='" + flightNumber + '\'' +
", capacity=" + capacity +
", passengers=" + passengers +
'}';
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
// 创建一个Flight对象
Flight flight = new Flight("Boeing 737", "MU5635", 189, 157);
// 输出对象属性
System.out.println(flight.getModel());
System.out.println(flight.getFlightNumber());
System.out.println(flight.getCapacity());
System.out.println(flight.getPassengers());
// 求载客率
System.out.println(flight.loadFactor());
// 重载toString方法
System.out.println(flight);
}
}
```
阅读全文