java 继承的案例
以下是一个简单的Java类继承的例子。在这个例子中,我们定义了一个基类Vehicle
,然后定义了两个派生类Car
和Truck
。
这个代码示例展示了面向对象编程中的继承和方法重写的基本用法。以下是对代码的详细分析:
类定义
基类
Vehicle
- 属性:
make
:表示车辆的制造商(如“Toyota”)。speed
:表示车辆的速度,但在示例中并未使用。- 构造方法:
Vehicle(String make)
:初始化make
属性。- 方法:
drive()
:打印出“Driving a [make]”的消息。子类
Car
继承自Vehicle
- 属性:
seatCount
:表示车内座位的数量。- 构造方法:
Car(String make, int seatCount)
:调用基类构造方法以初始化make
,并初始化seatCount
。- 方法:
drive()
:重写基类的drive()
方法,打印出“Driving a [make] with [seatCount] seats”的消息。子类
Truck
继承自Vehicle
- 属性:
payload
:表示卡车的载重(以千克为单位)。- 构造方法:
Truck(String make, int payload)
:调用基类构造方法以初始化make
,并初始化payload
。- 方法:
drive()
:重写基类的drive()
方法,打印出“Driving a [make] with payload of [payload] kg”的消息。
class Vehicle {// 基类属性protected String make;protected int speed;// 基类构造方法public Vehicle(String make) {this.make = make;}// 基类方法public void drive() {System.out.println("Driving a " + make);} }class Car extends Vehicle {// 车辆属性private int seatCount;// 构造方法public Car(String make, int seatCount) {super(make); // 调用基类构造方法this.seatCount = seatCount;}// 覆盖基类方法@Overridepublic void drive() {System.out.println("Driving a " + make + " with " + seatCount + " seats");} }class Truck extends Vehicle {// 卡车属性private int payload;// 构造方法public Truck(String make, int payload) {super(make); // 调用基类构造方法this.payload = payload;}// 覆盖基类方法@Overridepublic void drive() {System.out.println("Driving a " + make + " with payload of " + payload + " kg");} }// 测试代码 public class InheritanceExample {public static void main(String[] args) {Car car = new Car("Toyota", 5);Truck truck = new Truck("Ford", 1000);car.drive(); // 输出: Driving a Toyota with 5 seatstruck.drive(); // 输出: Driving a Ford with payload of 1000 kg} }