Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting child class to parent

I have two classes Product and ExtendedProduct. ExtendedProduct is derived from Product class. There are some more fields in ExtendedProduct class.

The problem is that when i cast ExtendedProduct into Product my Product object has the fields that ExtendedProduct has.

I just want to convert ExtendedProduct to Product class without any ExtendedProduct class' field appearing in Product class.

like image 358
MOD Avatar asked Jun 22 '26 19:06

MOD


1 Answers

As long as your ExtendedProduct IS a Product casting it to the latter won´t change anything to the casted instance because you reference the same object. So after all you just look at the same object from another perspective.

In order to decouple your object from its base-type you´d need to create a clone, a completely new instance of Product, e.g. by using a copy-constructor:

class Product {
    public Product(Product p) {
        this.MyProp = p.MyProp;   
    }
}

Now you can call this like:

var product = new Product(myExtended);

Now both objects are completely unrelated, changing MyProp on one doesn´t affect the other (in fact it does, if MyProp is a reference-type, so you´d need a deep clone instead).

However this sounds quite weird to me. Why would you want to "delete" the extended properties at all? You´ll need all the extra-information you provided earlier. You can simply cast to the parent-class which does not provide those properties at all:

var p = (Product) myExtendedProduct;

Now although p actually IS an instance of ExtendedProduct you can only access the properties from Product. This is a basic priciple of Polymorphism.

like image 175
MakePeaceGreatAgain Avatar answered Jun 25 '26 09:06

MakePeaceGreatAgain