Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about inheritance (assigning references).

 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,



This is allowed while



is not. Could anyone please give the reason as to why?

Thanks,
Raj.
 
Henry Wong
author
Marshal
Pie
Posts: 20907
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You really should name your classes something other than Parent and Child, if you want to understand inheritance in this regard... but... the reason the first is allowed is because a Child IS-A Parent, but a Parent may not be a Child.

This would make better sense, if you named parent and child to something else... Maybe name the parent class the Dog class. And name the child classes the Beagle class, the Akita class, the Terrier class, etc... The first is allowed because the Akita is a Dog, but a Dog may not be an Akita.

Henry
 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks,

I do understand the base class - child class relation and the idea of inheritance. I am interested in knowing what goes on behind the scenes. The real reason, I mean. Why is it that we can assign the derived class instance to that of a parent class while the other way round is not permitted?


Thanks,
Raj.
 
Henry Wong
author
Marshal
Pie
Posts: 20907
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raj Kamal wrote:
Why is it that we can assign the derived class instance to that of a parent class while the other way round is not permitted?


Another way to think about it is that a Child is a specialized version of a Parent. It can behave like the Parent, and be used everywhere a Parent is used, plus it has extra stuff / features. A Parent cannot be used in place of a Child because it doesn't have the stuff that is specific to a Child.

Henry

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic