Java 继承 - 将超类对象传递给子类可以简化吗?

Fel*_*lix 5 java inheritance

我们知道

String s = new Object();
Run Code Online (Sandbox Code Playgroud)

会导致错误:

incompatible types: Object cannot be converted to String
Run Code Online (Sandbox Code Playgroud)

因此,从下面的例子来看,我们不能这样做:

Car car = new Vehicle();
Run Code Online (Sandbox Code Playgroud)

但是对于 Java 来说,如果有这样的东西会有什么问题:

超级班:

    public class Vehicle {
        String color;
        int numberOfWheels;
        int maxSpeed;
        // etc.
    }
Run Code Online (Sandbox Code Playgroud)

子类:

    public class Car extends Vehicle {

        String engineType;
        String transmissionType;
        int numberOfDoors;
        // etc.

        Car(Vehicle vehicle) {
                            // the theoretical idea of passing
                            // the superclass object within a subclass
            super = vehicle;
        }
    }
Run Code Online (Sandbox Code Playgroud)

“超级=车辆;” 将允许我们一次性将先前设置的超类(车辆)的所有值传递给新的子类(汽车)。用法是:

    public class App {

        public static void main(String[] args) {

            Vehicle vehicle = new Vehicle();
            vehicle.color = "GREEN";
            vehicle.maxSpeed = 100;
            vehicle.numberOfWheels = 4;

            Car car = new Car(vehicle);

                                        // this would print: GREEN
            System.out.println("Car color is: " + car.color);
        }
    }
Run Code Online (Sandbox Code Playgroud)

也许已经有一种简单的方法可以做到类似的事情。

“启发那些仍处于黑暗中的人们……”

T.J*_*der 4

您可以执行类似的操作,但仍然需要提供Car特定信息(作为Car构造函数的参数,或默认值,或两者的组合)。

一种相当常见的方法是为in定义一个复制构造函数VehicleVehicle

public Vehicle(Vehicle other) {
    this.color = other.color;
    this.numberOfWheels = other.numberOfWheels;
    this.maxSpeed = other.maxSpeed;
}
Run Code Online (Sandbox Code Playgroud)

然后在 中Car,您使用该复制构造函数,然后充实细节Car

public Car(Vehicle v/*, and possibly car-specified args...*/) {
    super(v);
    // ...fill in `Car`-specific information
}
Run Code Online (Sandbox Code Playgroud)