Java:从父对象创建子类对象 [英] Java: Creating a subclass object from a parent object
问题描述
Newbie Java问题。说我有:
Newbie Java question. Say I have:
public class Car{
...
}
public class Truck extends Car{
...
}
我已经有一个Car对象,如何从这个Car对象创建一个新的Truck对象,以便所有的Car对象的值复制到我的新的Truck对象?
理想情况下,我可以这样做:
Suppose I already have a Car object, how do I create a new Truck object from this Car object, so that all the values of the Car object is copied into my new Truck object? Ideally I could do something like this:
Car c = new Car();
/* ... c gets populated */
Truck t = new Truck(c);
/* would like t to have all of c's values */
写我自己的复制构造函数?这将不得不更新每次汽车获得一个新的领域...
Would I have to write my own copy constructor? This would have to be updated everytime Car gets a new field...
推荐答案
是的,只是添加一个构造函数卡车。您可能想要向Car添加一个构造函数,但不一定是公共的:
Yes, just add a constructor to Truck. You will probably want to add a constructor to Car also, though not necessarily public:
public class Car {
protected Car(Car orig) {
...
}
public class Truck extends Car {
public Truck(Car orig) {
super(orig);
}
...
}
一般来说最好是让叶子(你可能想标记那些最终的)或抽象。
As a rule it's generally best to make classes either leaf (and you might want to mark those final) or abstract.
看起来像你想要一个 / code>对象,然后将相同的实例变成
Truck
。一个更好的方法是将行为委托给 Car
( Vehicle
)中的另一个对象。所以:
It looks as if you want a Car
object, and then have the same instance turn into a Truck
. A better way of doing this is to delegate behaviour to another object within Car
(Vehicle
). So:
public final class Vehicle {
private VehicleBehaviour behaviour = VehicleBehaviour.CAR;
public void becomeTruck() {
this.behaviour = VehicleBehaviour.TRUCK;
}
...
}
code> Cloneable ,那么您可以自动将对象复制到同一类的实例。但是还有一些问题,包括必须复制易变对象的每个字段,这些对象容易出错,并且禁止使用final。
If you implement Cloneable
then you can "automatically" copy an object to a instance of the same class. However there are a number of problems with that, including having to copy each field of mutable objects which is error-prone and prohibits the use of final.
这篇关于Java:从父对象创建子类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!