Java Reference
In-Depth Information
The output from the program is shown here:
This program creates a superclass called Sup and two subclasses of it, called Sub1 and
Sub2 . Sup declares a method called who( ) , and the subclasses override it. Inside the main(
) method, objects of type Sup , Sub1 , and Sub2 are declared. Also, a reference of type Sup ,
called supRef , is declared. The program then assigns a reference to each type of object to
supRef and uses that reference to call who( ) . As the output shows, the version of who( )
executed is determined by the type of object being referred to at the time of the call, not by
the class type of supRef .
Ask the Expert
Q :
Overridden methods in Java look a lot like virtual functions in C++. Is there a
similarity?
A : Yes. Readers familiar with C++ will recognize that overridden methods in Java are
equivalent in purpose and similar in operation to virtual functions in C++.
Why Overridden Methods?
As stated earlier, overridden methods allow Java to support run-time polymorphism. Poly-
morphism is essential to object-oriented programming for one reason: it allows a general
class to specify methods that will be common to all of its derivatives, while allowing sub-
classes to define the specific implementation of some or all of those methods. Overridden
methods are another way that Java implements the “one interface, multiple methods” as-
pect of polymorphism. Part of the key to successfully applying polymorphism is under-
standing that the superclasses and subclasses form a hierarchy that moves from lesser to
greater specialization. Used correctly, the superclass provides all elements that a subclass
can use directly. It also defines those methods that the derived class must implement on its
own. This allows the subclass the flexibility to define its own methods, yet still enforces a
Search WWH ::




Custom Search