Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Jul 18, 2000

Superclass Variables Referencing Subclasses

Question:
What is the advantage of declaring a variable as a superclass reference and then pointing that variable to an instance of a subclass? The way I see it, I can achieve the same end by declaring objects as subclass references and calling the required methods.

Answer:
Until you have to write some generic algorithms, the use of base class references and virtual methods can seem rather pointless. However, the technique is the only way to write generic functions in Java, given the absence of a C++-like template mechanism. If you look at the Java 2 Collections Framework, you will see how this technique is applied. All of the generic algorithms in the framework operate on some base type (e.g., List, Collection, etc.). But the classes that you use these methods on are always subclasses (e.g., ArrayList, Vector, etc.). Therefore, the answer to your question is that the technique is used so that you may write a piece of code only once that will operate on objects of many different types.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date