我们知道
String s = new Object();
会导致错误:
incompatible types: Object cannot be converted to String
因此,从下面的例子来看,我们不能这样做:
Car car = new Vehicle();
但是 Java 有这样的东西会有什么问题:
父类(super class):
public class Vehicle {
String color;
int numberOfWheels;
int maxSpeed;
// etc.
}
子类:
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;
}
}
'super = vehicle;'将允许我们传递先前设置的父类(super class)(车辆)的所有值 一次到新的子类(汽车)。 用法是:
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);
}
}
也许已经有一种类似的简单方法。
“启蒙那些还在黑暗中的人……”
最佳答案
您可以做类似的事情,但您仍然需要提供 Car
特定信息(作为 Car
构造函数的参数,或默认值,或两者的结合)。
一种相当常见的方法是在 Vehicle
中为 Vehicle
定义一个复制构造函数:
public Vehicle(Vehicle other) {
this.color = other.color;
this.numberOfWheels = other.numberOfWheels;
this.maxSpeed = other.maxSpeed;
}
然后在 Car
中,您使用该复制构造函数,然后充实 Car
详细信息:
public Car(Vehicle v/*, and possibly car-specified args...*/) {
super(v);
// ...fill in `Car`-specific information
}
关于Java 继承 - 可以简化将父类(super class)对象传递到子类的过程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906610/