Chopnut
Chopnut

Reputation: 647

Why in OO programming for casting objects instantiate super class and subclass in a variable?

For eg: ParentObj A = new ChildObj(); ((ChildObj) A).childMethod();

I see lots of instances like this in object oriented programming, would it be easier to just declare the ChildObj as ChildObj A = new ChildObj() instead of using the parent object as the starter of the of the creation of the object?

What would be the use cases of this example to any object oriented programming?

And will the A object be the ChildObj in this declaration or ParentObj?

Is there like a performance boost and such as to doing it this way or its a use case base thing if there is any?

thanks noob here.

Upvotes: 0

Views: 68

Answers (1)

Anil Agrawal
Anil Agrawal

Reputation: 3026

Its my personal opinion and mostly its true that there is no use case of such declaration, like

ParentObj A = new ChildObj();

We use to hide the child object under Parent references in below cases

  • We don't know, how the object initialized
  • We don't know the actual child class details
  • We have multiple child classes of same parent class and we just want to focus on overrided functions
  • We are bound with a contract and just using function that fulfills the contract (Interface scenarios)

These are some of use cases.

Upvotes: 2

Related Questions