创建一个车辆基类 并包含属性 在创建car和bicyle继承属性 调用相关方法并展示信息
时间: 2024-12-23 16:19:53 浏览: 5
当然,首先我们创建一个简单的`Vehicle`基类,包含通用的属性如`name`和`color`,以及一个抽象的方法`drive()`,表示所有车辆都能行驶。然后我们会为`Car`和`Bicycle`这两个子类提供具体的实现。
```java
// 车辆基类
public abstract class Vehicle {
private String name;
private String color;
// 构造函数
public Vehicle(String name, String color) {
this.name = name;
this.color = color;
}
// 获取属性的方法
public String getName() {
return name;
}
public String getColor() {
return color;
}
// 抽象方法 drive()
public abstract void drive();
// 显示信息的方法
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Color: " + color);
System.out.println("This is a vehicle.");
}
}
// Car 子类
public class Car extends Vehicle {
private int numDoors;
public Car(String name, String color, int numDoors) {
super(name, color);
this.numDoors = numDoors;
}
@Override
public void drive() {
System.out.println(getName() + " is driving with " + numDoors + " doors.");
}
}
// Bicycle 子类
public class Bicycle extends Vehicle {
private boolean hasBasket;
public Bicycle(String name, String color, boolean hasBasket) {
super(name, color);
this.hasBasket = hasBasket;
}
@Override
public void drive() {
System.out.println(getName() + " is cycling.");
}
}
```
现在我们可以创建这些类的对象并调用相关方法:
```java
public static void main(String[] args) {
Car car = new Car("Toyota Camry", "Blue", 4);
car.drive(); // 输出: Toyota Camry is driving with 4 doors.
car.displayInfo();
Bicycle bike = new Bicycle("Giant", "Red", true);
bike.drive(); // 输出: Giant is cycling.
bike.displayInfo();
}
```
阅读全文