0

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.

Chopnut
  • 607
  • 2
  • 8
  • 25
  • 1
    Have a look at [What does it mean to program to an interface](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – khelwood Jan 10 '17 at 12:21
  • 3
    What you're seeing is not a good example, it's a result of somebody not thinking clearly. It would be better to declare it as ChildObj. – Nathan Hughes Jan 10 '17 at 12:25
  • Thanks, I wonder about this alot although doable, why do it I asked. Also know about interfaces but which would make sense but a concrete class having a general in the declaration seems abit off. Could it be used for looping through array of child classes be easier to declare as parent class first and just do something about them later by through casting? mmmm – Chopnut Jan 10 '17 at 12:32
  • I have never seen the (pointless) construct you give as an example. I *have* seen the first line, lots of places. There are several uses for it: any time the type of the child object would cause some sort of problem with its use, but the parent wouldn't, I would expect to see this. There is no performance issue; casting is a compile-time operation. The object will be a child object; that was what was created, and neither the declaration nor the cast will change it. – arcy Jan 10 '17 at 13:06

1 Answers1

2

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.

Anil Agrawal
  • 2,748
  • 1
  • 24
  • 31