File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes base class and derived class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "base class and derived class" Watch "base class and derived class" New topic

base class and derived class

Padma Prasad
Ranch Hand

Joined: Sep 16, 2002
Posts: 76
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

Joined: May 26, 2003
Posts: 33124

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Padma Prasad
Ranch Hand

Joined: Sep 16, 2002
Posts: 76
Thanks much, Jeanne.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
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).

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Hari Narayana

Joined: Apr 07, 2004
Posts: 2
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.

Hari Narayana (MCA)
Padma Prasad
Ranch Hand

Joined: Sep 16, 2002
Posts: 76
Thanks much for the URL's. "How my Dog Learned Polymorphism" is real good and fun. Sure anybody can easily understand polymorphism with this.
I agree. Here's the link:
subject: base class and derived class
It's not a secret anymore!