Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

doubt with reference variables  RSS feed

 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Why does the line B b = new A(); throw compilation error?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Every Hammer IS-A Tool, but not every Tool is a Hammer. Some Tools are Screwdrivers, and some are just plain Tools. Either way, not a Hammer.

Tool t says "reference variable t will point to an object that IS-A Tool." Then the = new Hammer() part gives it a reference to a Hammer, and that Hammer IS-A Tool, so it's all good.

Hammer h says "reference variable h will point to an object that IS-A Hammer." Then the = new Tool() part gives it a reference to a Tool, but that Tool is not a Hammer, so it's no good.


It's exactly the same thing as this:

 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the very clear and precise explanation Jeff
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!