Java Tutorial – 14 – Overriding

A member in a subclass can redefine a member
in its superclass. This is most often done to give instance methods new implementations.
To demonstrate we’ll override Rectangle’s getArea method by redeclaring it in Triangle
with the same method signature. The signature includes the name, parameters, and return
type of the method. The access level however can be changed to allow for more access but
not less access than the redefined method. In order to show that this override was intentional
Java wants us to add the @Override annotation. This annotation was added in Java 1.5 to prevent
accidental overrides, although it’s not mandatory to use it. Now, if we create a Triangle and call the
getArea method Triangle’s version of the method will get called. If we upcast the Triangle
to a Rectangle Triangle’s version will still get called, because Rectangle’s version has
been overridden. Note that this is only true for instance methods and not for class methods.
If we add a class method called newArea to Rectangle and redefine it in Triangle, then
Triangle’s version will only hide Rectangle’s implementation and therefore we won’t use
the override annotation. Calling newArea from Triangle’s interface will as expected invoke
Triangle’s version, but calling the method from Rectangle’s interface will now invoke
Rectangle’s implementation. Redefined instance methods will always be overridden in Java
and redefined class methods will always be hidden and there is no way to change that
as can be done in for example C++ or C#. If we want to prevent an instance method from
being overridden in subclasses we can declare it using the final method modifier. Note that
the order of these modifiers is not optional and if we mix up the order the compiler will
point that out. An overridden method can still be accessed
from inside the subclass’ instance methods using the super keyword, which is a reference
to the current instance of the superclass. Another place where the super keyword can
be used is on the first line of a constructor. The super keyword is then used as a function
call that invokes the superclass’s constructor. If the first line of a constructor is not
a call to another constructor the Java compiler will automatically add a call to the superclass’
no parameter constructor in order to make sure that all ancestor classes of this class
are properly constructed. Note that because we added a constructor to Rectangle Java does
not create a default constructor for the class which gives us an error. To fix this we need
to manually add a no parameter constructor to Rectangle.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


Leave a Reply

Your email address will not be published. Required fields are marked *