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.

8.4.10 Examples of Method Declarations CLASSES<br />

234<br />

RealPoint from outside the body of RealPoint, no matter what the type of the<br />

variable we may use to hold the reference to the object. Thus, we see that fields<br />

and methods behave differently: hiding is different from overriding.<br />

8.4.10.5 Example: Invocation of Hidden Class Methods<br />

A hidden class (static) method can be invoked by using a reference whose type<br />

is the class that actually contains the declaration of the method. In this respect,<br />

hiding of static methods is different from overriding of instance methods. <strong>The</strong><br />

example:<br />

class Super {<br />

static String greeting() { return "Goodnight"; }<br />

String name() { return "Richard"; }<br />

}<br />

class Sub extends Super {<br />

static String greeting() { return "Hello"; }<br />

String name() { return "Dick"; }<br />

}<br />

class Test {<br />

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

Super s = new Sub();<br />

System.out.println(s.greeting() + ", " + s.name());<br />

}<br />

}<br />

produces the output:<br />

Goodnight, Dick<br />

because the invocation of greeting uses the type of s, namely Super, to figure<br />

out, at compile time, which class method to invoke, whereas the invocation of<br />

name uses the class of s, namely Sub, to figure out, at run time, which instance<br />

method to invoke.<br />

DRAFT<br />

8.4.10.6 Large Example of Overriding<br />

Overriding makes it easy for subclasses to extend the behavior of an existing<br />

class, as shown in this example:<br />

import java.io.OutputStream;<br />

import java.io.IOException;<br />

class BufferOutput {<br />

private OutputStream o;<br />

BufferOutput(OutputStream o) { this.o = o; }

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

Saved successfully!

Ooh no, something went wrong!