Java: Creating a subclass object from a parent object

前端 未结 11 2266
攒了一身酷
攒了一身酷 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:06

    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.

    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;
        } 
        ...
    }
    

    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.

    0 讨论(0)
  • 2020-12-09 15:07

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

    Not at all!

    Try this way:

    public class Car{
        ...
    }
    
    public class Truck extends Car{
        ...
    
        public Truck(Car car){
            copyFields(car, this);
        }
    }
    
    
    public static void copyFields(Object source, Object target) {
            Field[] fieldsSource = source.getClass().getFields();
            Field[] fieldsTarget = target.getClass().getFields();
    
            for (Field fieldTarget : fieldsTarget)
            {
                for (Field fieldSource : fieldsSource)
                {
                    if (fieldTarget.getName().equals(fieldSource.getName()))
                    {
                        try
                        {
                            fieldTarget.set(target, fieldSource.get(source));
                        }
                        catch (SecurityException e)
                        {
                        }
                        catch (IllegalArgumentException e)
                        {
                        }
                        catch (IllegalAccessException e)
                        {
                        }
                        break;
                    }
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-09 15:17

    Yes, you have to do this manually. You'll also need to decide how "deeply" to copy things. For instance, suppose the Car has a collection of tyres - you could do a shallow copy of the collection (such that if the original object changes the contents of its collection, the new object would see the change too) or you could do a deep copy which created a new collection.

    (This is where immutable types like String often come in handy - there's no need to clone them; you can just copy the reference and know that the contents of the object won't change.)

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-12-09 15:17

    You will need a copy constructor, but your copy constructor can use reflection to find the common fields between the two objects, get their values from the "prototype" object, and set them on the child object.

    0 讨论(0)
  • 2020-12-09 15:17

    I know this is an OLD question, but I hate to leave out dated answers when things have improved.

    Using JSON is much easier. Convert it to JSON and back again as child.

    Here is an Android Kotlin Example.

        val gson = Gson()    
        val childClass = gson.fromJson(
            gson.toJson(parentObject), 
            object: TypeToken<ChildObject>(){}.type
        ) as ChildObject
    

    I think in Java it would be basically.

    Gson gson = new Gson()
    ChildObject child = (ChildObject) gson.fromJson(
        gson.toJson(parentObject),
        TypeToken<ChildObject>(){}.getType()
    ) 
    

    And you're done, no messiness, just simple json in, json out. If you don't have gson, I'm sure you have other json options available to you.

    It's a WHOLE lot cleaner and faster than doing reflection and all that craziness.

    0 讨论(0)
提交回复
热议问题