java编写汽车父类和子类
时间: 2024-02-11 20:35:32 浏览: 24
好的,下面是Java代码示例:
```java
// 汽车父类
public class Car {
private String brand; // 品牌
private String color; // 颜色
private int maxSpeed; // 最大速度
// 构造方法
public Car(String brand, String color, int maxSpeed) {
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}
// Getter和Setter方法
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
// 加速方法
public void speedUp() {
System.out.println("汽车加速");
}
// 刹车方法
public void brake() {
System.out.println("汽车刹车");
}
}
// 轿车子类
public class Sedan extends Car {
private int seats; // 座位数
// 构造方法
public Sedan(String brand, String color, int maxSpeed, int seats) {
super(brand, color, maxSpeed);
this.seats = seats;
}
// Getter和Setter方法
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
// 载人方法
public void carryPeople() {
System.out.println("轿车可以载人,座位数为:" + seats);
}
}
```
在这个例子中,`Car` 是汽车的父类,包含了汽车的基本属性和方法。`Sedan` 是轿车的子类,继承了 `Car` 类,并添加了轿车特有的属性和方法。子类可以使用父类的属性和方法,同时也可以重写父类的方法。