Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The ability of a subclass to override a method in its superclass allows a class to inherit from a superclass whose behavior is "close enough" and then override methods as needed.For example, all classes are descendents of the
Object
class.Object
contains thetoString
method, which returns aString
object containing the name of the object's class and its hash code. Most, if not all, classes will want to override this method and print out something meaningful for that class.Let's resurrect the
Stack
class example and override thetoString
method. The output oftoString
should be a textual representation of the object. For theStack
class, a list of the items in the stack would be appropriateThe return type, method name, and number and type of the parameters for the overriding method must match those in the overridden method. The overriding method can have a different throws clause as long as it doesn't declare any types not declared by the throws clause in the overridden method. Also, the access specifier for the overriding method can allow more access than the overridden method, but not less. For example, apublic class Stack { private Vector items; // code for Stack's methods and constructor not shown // overrides Object's toString method public String toString() { int n = items.size(); StringBuffer result = new StringBuffer(); result.append("["); for (int i = 0; i < n; i++) { result.append(items.elementAt(i).toString()); if (i < n-1) result.append(","); } result.append("]"); return result.toString(); } }protected
method in the superclass can be madepublic
but notprivate
.
Sometimes, you don't want to completely override a method. Rather, you want to add more functionality to it. To do this, simply call the overridden method using thesuper
keyword. For example,super.overriddenMethodName();
A subclass cannot override methods that are declared final in the superclass (by definition, final methods cannot be overridden). If you attempt to override a final method, the compiler displays an error message similar to the following and refuses to compile the program:Also, a subclass cannot override methods that are declaredFinalTest.java:7: Final methods can't be overridden. Method void iamfinal() is final in class ClassWithFinalMethod. void iamfinal() { ^ 1 errorstatic
in the superclass. In other words, a subclass cannot override a class method. A subclass can hide astatic
method in the superclass by declaring astatic
method in the subclass with the same signature as thestatic
method in the superclass.
A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract. The upcoming Writing Abstract Classes and Methods section discusses abstract classes and methods in detail.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |