This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Java in General and the fly likes reference variable for class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "reference variable for class" Watch "reference variable for class" New topic

reference variable for class

tilak kumar

Joined: Feb 16, 2005
Posts: 15
what is the use of assigning subclass reference to super class reference
Timmy Marks
Ranch Hand

Joined: Dec 01, 2003
Posts: 226
I am going to assume you mean to ask what the advantage of upcasting (referring to a child with a reference of the parent's type) is.

If that is the case, then imagine a class Person with subclasses for Man, Woman, Boy and Girl. The class Person defines a method called performDailyRoutine(). Obviously, the different types of person will override the method. Now if we were to have a class Family with a List of Persons, we could Iterate through the List, cast the Objects to Persons and call performDailyRoutine() without having to regard what actual class the Person is. The same goes for classes that implement a certain Interface, so you can also use a reference to an Interface that is implemented by all classes within a collection.

Does this make sense?
I agree. Here's the link:
subject: reference variable for class
It's not a secret anymore!