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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: