Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

base class and derived class

 
Padma Prasad
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lets say we have these classes.
class Tree {}
class Pine extends Tree{}
class test{
Tree tree = new Pine();
}
now, we all know that tree is now an instance of Pine and Tree but actually derives Pine. My question is Pine anyway extends Tree so an object of Pine also gets the characteristics of Tree. so, we can say
Pine tree = new Pine();
why is the necessity of the statement
Tree tree = new Pine();
In which scenario does this kind of object creation arise.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34410
346
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would use this if you wanted to make sure you were only using methods available on Tree. That way, you could change to a different type of tree later without having to change the code.
 
Padma Prasad
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks much, Jeanne.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might like a reading of the "How my Dog Learned Polymorphism" story in the JavaRanch Campfire Stories.
Also, Tony Sintes' article Abstract classes and interfaces practicum includes a decent introduction to the concept and advantages of "programming to the interface" (or abstract base type as the case may be).
 
Hari Narayana
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This Concept is actually called upcasting. This is actually done when u want a limited functionality to ur class. Through the base class, u are accessing ur derived class members.
 
Padma Prasad
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dirk,
Thanks much for the URL's. "How my Dog Learned Polymorphism" is real good and fun. Sure anybody can easily understand polymorphism with this.
regards,
Padma.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic