Java Reference
In-Depth Information
Overriding Methods
When you call an object's method, Java looks for that method definition in the object's
class. If it doesn't find one, it passes the method call up the class hierarchy until a
method definition is found. Method inheritance enables you to define and use methods
repeatedly in subclasses without having to duplicate the code.
However, there might be times when you want an object to respond to the same methods
but have different behavior when that method is called. In that case, you can override the
method. To override a method, define a method in a subclass with the same signature as
a method in a superclass. Then, when the method is called, the subclass method is found
and executed instead of the one in the superclass.
Creating Methods That Override Existing Methods
To override a method, all you have to do is create a method in your subclass that has the
same signature (name and argument list) as a method defined by your class's superclass.
Because Java executes the first method definition it finds that matches the signature, the
new signature hides the original method definition.
Here's a simple example; Listing 5.7 contains two classes: Printer , which contains a
method called printMe() that displays information about objects of that class, and
SubPrinter , a subclass that adds a z instance variable to the class.
LISTING 5.7
The Full Text of Printer.java
1: class Printer {
2: int x = 0;
3: int y = 1;
4:
5: void printMe() {
6: System.out.println(“x is “ + x + “, y is “ + y);
7: System.out.println(“I am an instance of the class “ +
8: this.getClass().getName());
9: }
10: }
11:
12: class SubPrinter extends Printer {
13: int z = 3;
14:
15: public static void main(String[] arguments) {
16: SubPrinter obj = new SubPrinter();
17: obj.printMe();
18: }
19: }
 
 
Search WWH ::




Custom Search