10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

15.12.4 Runtime Evaluation of Method Invocation EXPRESSIONS<br />

480<br />

15.12.4.8 Example: Overriding<br />

In the example:<br />

class Point {<br />

final int EDGE = 20;<br />

int x, y;<br />

void move(int dx, int dy) {<br />

x += dx; y += dy;<br />

if (Math.abs(x) >= EDGE || Math.abs(y) >= EDGE)<br />

clear();<br />

}<br />

void clear() {<br />

System.out.println("\tPoint clear");<br />

x = 0; y = 0;<br />

}<br />

}<br />

class ColoredPoint extends Point {<br />

int color;<br />

void clear() {<br />

System.out.println("\tColoredPoint clear");<br />

super.clear();<br />

color = 0;<br />

}<br />

}<br />

the subclass ColoredPoint extends the clear abstraction defined by its superclass<br />

Point. It does so by overriding the clear method with its own method,<br />

which invokes the clear method of its superclass, using the form super.clear.<br />

This method is then invoked whenever the target object for an invocation of<br />

clear is a ColoredPoint. Even the method move in Point invokes the clear<br />

method of class ColoredPoint when the class of this is ColoredPoint, as<br />

shown by the output of this test program:<br />

class Test {<br />

public static void main(String[] args) {<br />

Point p = new Point();<br />

System.out.println("p.move(20,20):");<br />

p.move(20, 20);<br />

ColoredPoint cp = new ColoredPoint();<br />

System.out.println("cp.move(20,20):");<br />

cp.move(20, 20);<br />

p = new ColoredPoint();<br />

System.out.println("p.move(20,20), p colored:");<br />

p.move(20, 20);<br />

DRAFT

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!