Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Application Security Testing: An Integral Part of DevOps

Superclass Variables Referencing Subclasses

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.

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.



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