Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reference variable for class

 
tilak kumar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the use of assigning subclass reference to super class reference
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic