Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "clone" an object into a subclass object?

I have a class A and a class B that inherits class A and extends it with some more fields.

Having an object a of type A, how can I create an object b of type B that contains all data that object a contained?

I have tried a.MemberwiseClone() but that only gives me another type A object. And I cannot cast A into B since the inheritance relationship only allows the opposite cast.

What is the right way to do this?

like image 495
Vizu Avatar asked Jul 07 '09 15:07

Vizu


People also ask

Can you create an object from a subclass?

In inheritance, subclass acquires super class properties. An important point to note is, when a subclass object is created, a separate object of a superclass object will not be created. Only a subclass object is created that has superclass variables.

How do you copy an object in Java?

The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.

Can an object be a subclass of another class?

Can an object be a subclass of another object? A. Yes—as long as single inheritance is followed.

Can we assign superclass object to subclass?

No. It makes zero sense to allow that. The reason is because subclasses generally define additional behavior. If you could assign a superclass object to a subclass reference, you would run into problems at runtime when you try to access class members that don't actually exist.


1 Answers

I would add a copy constructor to A, and then add a new constructor to B that takes an instance of A and passes it to the base's copy constructor.

like image 180
Bryan Avatar answered Sep 18 '22 12:09

Bryan