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?
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.
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 object? A. Yes—as long as single inheritance is followed.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With