Simple but confusing code... Parent obj1 = new Parent(); Parent obj2 = new Child();

Simple but confusing code... Parent obj1 = new Parent(); Parent obj2 = new Child();

Hi friends I got confused in the below code snippet:

Parent obj1 = new Parent(); Parent obj2 = new Child();

Here we have created obj1 object of class parent, so it is witten as, Parent obj1 = new Parent(); well its ok.

Then we create Parent obj2 = new Child(); <--------------- here in this code what is the purpose and use to assign obj2 to child(); I have also seen this while learning Collection, that's why I AM GETTING MORE CONFUSED. Please explain in detail....

View Answers

October 31, 2012 at 2:59 PM

The code does not start obj2 as a Parent. It created a Child and then assigns it to obj2, which is declared to be of type Parent. This is legal because Child is a subclass of Parent. In this case obj2 was declared to be a Parent presumably.


October 31, 2012 at 7:30 PM

Thanks a ton Admin :) that cleared my doubt.









Related Tutorials/Questions & Answers:

Ads