如何用java创造三个类解决汽车问题
时间: 2024-10-25 12:06:31 浏览: 8
在Java中,我们可以创建一个简单的类体系来表示汽车的问题,通常包括一个基础类`Car`,然后通过继承和多态来扩展两个特定类型的车辆:`ElectricCar`和`GasCar`。这里是一个基本的例子:
1. **基础类(Car)**:
```java
public abstract class Car {
private String model;
public Car(String model) {
this.model = model;
}
// 公共方法
public String getModel() {
return model;
}
// 抽象方法,需要在子类中实现
public abstract void drive();
public abstract void refuel();
}
```
2. **子类(ElectricCar 和 GasCar)**:
```java
public class ElectricCar extends Car {
public ElectricCar(String model) {
super(model);
}
@Override
public void drive() {
System.out.println(getModel() + " is driving on electric power.");
}
@Override
public void refuel() {
System.out.println("Electric car doesn't need refueling.");
}
}
public class GasCar extends Car {
private double fuelCapacity;
public GasCar(String model, double fuelCapacity) {
super(model);
this.fuelCapacity = fuelCapacity;
}
@Override
public void drive() {
System.out.println(getModel() + " is driving with gasoline.");
}
@Override
public void refuel(double amount) {
if (amount > 0 && fuelCapacity + amount <= Double.MAX_VALUE) {
fuelCapacity += amount;
System.out.println("Refueled " + amount + " liters of gasoline.");
} else {
System.out.println("Fuel capacity cannot be exceeded.");
}
}
}
```
在这个例子中,`drive()`和`refuel()`方法是在`Car`类中声明为抽象的,因此每个子类都必须提供它们的具体实现。通过这种方式,你可以创建任意数量的`ElectricCar`实例和`GasCar`实例,并按照它们各自的特性和行为来操作。
阅读全文