Java: Creating a subclass object from a parent object

前端 未结 11 2310
攒了一身酷
攒了一身酷 2020-12-09 14:28

Newbie Java question. Say I have:

public class Car{
  ...
}

public class Truck extends Car{
  ...
}

Suppose I already have a Car object, h

11条回答
  •  轮回少年
    2020-12-09 15:17

    Would I have to write my own copy constructor? This would have to be updated everytime Car gets a new field...

    Essentially, yes - you can't just convert an object in Java.

    Fortunately you don't have to write all the code yourself - look into commons-beanutils, specifically methods like cloneBean. This has the added advantage that you don't have to update it every time it gets a new field!

提交回复
热议问题