我们知道
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);
}
}
也许已经有一种类似的简单方法。
“启发那些仍在黑暗中的人……”
答案 0 :(得分:3)
您可以执行类似的操作,但仍需要提供特定于Car
的信息(作为Car
构造函数的参数,或者是默认值,或两者的组合)。 / p>
一种相当普遍的方法是在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
}
答案 1 :(得分:1)
因此,在下面的示例中,我们不能这样做:
Car car = new Vehicle();
是的,您不能这样做,因为Vehicle
是Car
的父项。因此,您可以这样做:
Vehicle car = new Car();
这是多态性的一部分。而做您想做的事情的简单方法是
首先将构造函数添加到Vehicle
类中,
public Vehicle(String color, int numberOfWheels, int maxSpeed) {
this.color = color;
//other two assignment
}
然后在Car
类构造函数中,
public Car(String color, int numberOfWheels, int maxSpeed, String engineType, String transmissionType, int numberOfDoors) {
super(color, numberOfWheels, maxSpeed);
this.engineType = engineType;
this.transmissionType = transmissionType;
this.numberOfDoors = numberOfDoors;
}//keep remember, you can also use constructor overloading.
现在放在main()
内,
Vehicle car = new Car(/*arguments*/);
答案 2 :(得分:0)
您可以执行类似的操作
public Car(Vehicle v){
super(v)
// assuming super has constructor to copy from Vehicle
}
答案 3 :(得分:0)
这样做不是什么好事,因为在car上调用的任何方法都是基类中找到的方法,或者至少是正常情况下发生的方法,反之亦然。被调用的是对象的方法,而不是变量的方法。
答案 4 :(得分:0)
由于您将Vehicle声明为非抽象类,因此JVM将其视为可实例化类。
super,这是在面向对象语言中具有特殊含义的参考。如果您熟悉面向对象的编译器和运行时环境,那么您将了解为什么无法访问派生类。
想象一下,您必须继承那些继承Vehicle的具体类,那么您想引用哪个具体类呢?
另一个问题,编译器根据模式在堆中占用空间,它将所有信息(属性和行为)收集为对象的单个构建块,覆盖属性并为所有方法保留空间,此引用表示所有方法都是可靠的在Concert类和super类的非重写方法中定义(super类只是开发中的概念,运行时空间将与它的Concert类合并),super引用意味着被其子类覆盖的所有方法,但仍然是该方法的代码空间由构件块寻址。
通过这些简单的问题,您将发现更改超级引用或该引用是不可能的,并且将完善OOP概念。