[英]Java: How can I instantiate a parent object from child without using parent constructor?
Here's the example:这是示例:
public class Car{
private float param;
public Car(float rawParam) {
// process rawParam before assign it to this.param
this.param = rawParam * 2;
}
}
public class Truck extends Car{
public Truck(Car car) {
// How do I instantiate Car?
}
}
There's no default constructor, so I can't just create some arbitrary parent object then clone the passed car by reflection.没有默认构造函数,所以我不能只是创建一些任意的父对象,然后通过反射克隆传递的汽车。 The only constructor provided needs some raw params which are unknown to the parent object itself.提供的唯一构造函数需要一些父对象本身未知的原始参数。 How can I instantiate Car and Truck in this case?在这种情况下,如何实例化 Car 和 Truck? Thanks!谢谢!
If what you want his instance a Truck
based on the value of another instance of Car
, so copy a Car
into a Truck
, using your constructor, this COULD look like this :如果你想自己的实例的什么Truck
基础上的另一个实例的值Car
,所以复制Car
到Truck
,用你的构造,这看起来是这样的:
public Truck(Car car) {
super(car.getParam());
}
Assuming getParam
exists and return the value you want!!假设getParam
存在并返回您想要的值!!
Note that if car
is null, you will received a RuntimeException
(a NullPointerException
), and you can't check that since Super
need to be the first statement.请注意,如果car
为空,您将收到一个RuntimeException
(一个NullPointerException
),并且您无法检查它,因为Super
需要是第一个语句。
Well, you can but in some ways, like using a ternary operation :嗯,你可以,但在某些方面,比如使用三元运算:
public Truck(Car car) {
super(car != null ? car.getParam() : -1);
}
There are other solution but this is not the point here.还有其他解决方案,但这不是重点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.