devxlogo

Superclass Variables Referencing Subclasses

Superclass Variables Referencing Subclasses

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

Answer:
Until you have to write some generic algorithms, the use of base classreferences 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 atthe Java 2 Collections Framework, you will see how this technique isapplied. All of the generic algorithms in the framework operate onsome base type (e.g., List, Collection, etc.). But the classes that youuse these methods on are always subclasses (e.g., ArrayList, Vector,etc.). Therefore, the answer to your question is that the techniqueis used so that you may write a piece of code only once that willoperate on objects of many different types.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist