我们知道
String s = new Object();
会导致错误:
incompatible types: Object cannot be converted to String
因此,从下面的例子中,我们不能这样做:
Car car = new Vehicle();
但是如果 Java 有这样的东西会有什么问题:
超级班:
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;
}
}
'超级 = 车辆;' 将允许我们一次性将先前设置的超类(车辆)的所有值传递给新的子类(汽车)。用法是:
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);
}
}
也许已经有一种简单的方法可以类似地做到这一点。
“照亮那些仍然在黑暗中的人......”
泛舟湖上清波郎朗
手掌心
撒科打诨
相关分类