| CHAPTER 8: Class Declarations |
Previous |
Java Language |
Index |
Next |
A method declares executable code that can be invoked, passing a fixed number of values as arguments.
MethodDeclaration: MethodHeader MethodBody MethodHeader: MethodModifiersopt ResultType MethodDeclarator Throwsopt ResultType: Type void MethodDeclarator: Identifer ( FormalParameterListopt )
The MethodModifiers are described in S8.4.3, the Throws clause in S8.4.4, and the MethodBody in S8.4.5. A method declaration either specifies the type of value that the method returns or uses the keyword void to indicate that the method does not return a value.
The Identifier in a MethodDeclarator may be used in a name to refer to the method. A class can declare a method with the same name as the class or a field of the class.
For compatibility with older versions of Java, a declaration form for a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the parameter list. This is supported by the obsolescent production:
MethodDeclarator: MethodDeclarator [ ]
but should not be used in new Java code.
It is a compile-time error for the body of a class to have as members two methods with the same signature (S8.4.2) (name, number of parameters, and types of any parameters). Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (S6.5).
The formal parameters of a method, if any, are specified by a list of comma-separated parameter specifiers. Each parameter specifier consists of a type and an identifier (optionally followed by brackets) that specifies the name of the parameter:
FormalParameterList: FormalParameter FormalParameterList , FormalParameter FormalParameter: Type VariableDeclaratorId
The following is repeated from S8.3 to make the presentation here clearer:
VariableDeclaratorId: Identifier VariableDeclaratorId [ ]
If a method has no parameters, only an empty pair of parentheses appears in the method's declaration.
If two formal parameters are declared to have the same name (that is, their declarations mention the same Identifier), then a compile-time error occurs.
When the method is invoked (S15.11), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method to refer to the formal parameter.
The scope of formal parameter names is the entire body of the method. These parameter names may not be redeclared as local variables or exception parameters within the method; that is, hiding the name of a parameter is not permitted.
Formal parameters are referred to only using simple names, never by using qualified names (S6.6).
The signature of a method consists of the name of the method and the number and types of formal parameters to the method. A class may not declare two methods with the same signature, or a compile-time error occurs. The example:
class Point implements Move {
int x, y;
abstract void move(int dx, int dy);
void move(int dx, int dy) { x += dx; y += dy; }
}
causes a compile-time error because it declares two move methods with the same signature. This is an error even though one of the declarations is abstract .
MethodModifiers: MethodModifier MethodModifiers MethodModifier MethodModifier: one of public protected private abstract static final synchronized native
The access modifiers public , protected , and private are discussed in S6.6. A compile-time error occurs if the same modifier appears more than once in a method declaration, or if a method declaration has more than one of the access modifiers public , protected , and private . A compile-time error occurs if a method declaration that contains the keyword abstract also contains any one of the keywords private , static , final , native , or synchronized .
If two or more method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for MethodModifier.
An abstract method declaration introduces the method as a member, providing its signature (name and number and type of parameters), return type, and throws clause (if any), but does not provide an implementation. The declaration of an abstract method m must appear within an abstract class (call it A); otherwise a compile-time error results. Every subclass of A that is not abstract must provide an implementation for m, or a compile-time error occurs. More precisely, for every subclass C of the abstract class A, if C is not abstract , then there must be some class B such that all of the following are true:
If there is no such class B, then a compile-time error occurs.
It is a compile-time error for a private method to be declared abstract . It would be impossible for a subclass to implement a private abstract method, because private methods are not visible to subclasses; therefore such a method could never be used.
It is a compile-time error for a static method to be declared abstract .
It is a compile-time error for a final method to be declared abstract .
An abstract class can override an abstract method by providing another abstract method declaration. This can provide a place to put a documentation comment (Chapter 18), or to declare that the set of checked exceptions (S11.2) that can be thrown by that method, when it is implemented by its subclasses, is to be more limited. For example, consider this code:
class BufferEmpty extends Exception {
BufferEmpty() { super(); }
BufferEmpty(String s) { super(s); }
}
class BufferError extends Exception {
BufferError() { super(); }
BufferError(String s) { super(s); }
}
public interface Buffer {
char get() throws BufferEmpty, BufferError;
}
public abstract class InfiniteBuffer implements Buffer {
abstract char get() throws BufferError;
}
The overriding declaration of method get in class InfiniteBuffer states that method get in any subclass of InfiniteBuffer never throws a BufferEmpty exception, putatively because it generates the data in the buffer, and thus can never run out of data.
An instance method that is not abstract can be overridden by an abstract method. For example, we can declare an abstract class Point that requires its subclasses to implement toString if they are to be complete, instantiable classes:
abstract class Point {
int x, y;
public abstract String toString();
}
This abstract declaration of toString overrides the non-abstract toString method of class Object (S20.1.2). (Class Object is the implicit direct superclass of class Point .) Adding the code:
class ColoredPoint extends Point {
int color;
public String toString() {
return super.toString() + ": color " + color; // error
}
}
results in a compile-time error because the invocation super.toString() refers to method toString in class Point , which is abstract and therefore cannot be invoked. Method toString of class Object can be made available to class ColoredPoint only if class Point explicitly makes it available through some other method, as in:
abstract class Point {
int x, y;
public abstract String toString();
protected String objString() { return super.toString(); }
}
class ColoredPoint extends Point {
int color;
public String toString() {
return objString() + ": color " + color; // correct
}
}
A method that is declared static is called a class method. A class method is always invoked without reference to a particular object. An attempt to reference the current object using the keyword this or the keyword super in the body of a class method results in a compile time error. It is a compile-time error for a static method to be declared abstract .
A method that is not declared static
is called an instance method, and sometimes called a non-static
method). An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this
and super
refer during execution of the method body.
A method can be declared final to prevent subclasses from overriding or hiding it. It is a compile-time error to attempt to override or hide a final method.
A private method and all methods declared in a final class (S8.1.2.2) are implicitly final , because it is impossible to override them. It is permitted but not required for the declarations of such methods to redundantly include the final keyword.
It is a compile-time error for a final method to be declared abstract .
At run-time, a machine-code generator or optimizer can easily and safely "inline" the body of a final method, replacing an invocation of the method with the code in its body, as in the example:
final class Point {
int x, y;
void move(int dx, int dy) { x += dx; y += dy; }
}
class Test {
public static void main(String[] args) {
Point[] p = new Point[100];
for (int i = 0; i < p.length; i++) {
p[i] = new Point();
p[i].move(i, p.length-1-i);
}
}
}
Here, inlining the method move of class Point in method main would transform the for loop to the form:
for (int i = 0; i < p.length; i++) {
p[i] = new Point();
Point pi = p[i];
pi.x += i;
pi.y += p.length-1-i;
}
The loop might then be subject to further optimizations.
Such inlining cannot be done at compile time unless it can be guaranteed that Test
and Point
will always be recompiled together, so that whenever Point
-and specifically its move
method-changes, the code for Test.main
will also be updated.
A method that is native is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN, or assembly language. The body of a native method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.
A compile-time error occurs if a native method is declared abstract .
For example, the class RandomAccessFile of the standard package java.io might declare the following native methods:
package java.io;
public class RandomAccessFile
implements DataOutput, DataInput
{ . . .
public native void open(String name, boolean writeable)
throws IOException;
public native int readBytes(byte[] b, int off, int len)
throws IOException;
public native void writeBytes(byte[] b, int off, int len)
throws IOException;
public native long getFilePointer() throws IOException;
public native void seek(long pos) throws IOException;
public native long length() throws IOException;
public native void close() throws IOException;
}
A synchronized method acquires a lock (S17.1) before it executes. For a class (static) method, the lock associated with the Class object (S20.3) for the method's class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used. These are the same locks that can be used by the synchronized statement (S14.17); thus, the code:
class Test {
int count;
synchronized void bump() { count++; }
static int classCount;
static synchronized void classBump() {
classCount++;
}
}
has exactly the same effect as:
class BumpTest {
int count;
void bump() {
synchronized (this) {
count++;
}
}
static int classCount;
static void classBump() {
try {
synchronized (Class.forName("BumpTest")) {
classCount++;
}
} catch (ClassNotFoundException e) {
...
}
}
}
The more elaborate example:
public class Box {
private Object boxContents;
public synchronized Object get() {
Object contents = boxContents;
boxContents = null;
return contents;
}
public synchronized boolean put(Object contents) {
if (boxContents != null)
return false;
boxContents = contents;
return true;
}
}
defines a class which is designed for concurrent use. Each instance of the class Box has an instance variable contents that can hold a reference to any object. You can put an object in a Box by invoking put , which returns false if the box is already full. You can get something out of a Box by invoking get , which returns a null reference if the box is empty.
If put and get were not synchronized , and two threads were executing methods for the same instance of Box at the same time, then the code could misbehave. It might, for example, lose track of an object because two invocations to put occurred at the same time.
See Chapter 17 for more discussion of threads and locks.
A throws clause is used to declare any checked exceptions (S11.2) that can result from the execution of a method or constructor:
Throws: throws ClassTypeList ClassTypeList: ClassType ClassTypeList , ClassType
A compile-time error occurs if any ClassType mentioned in a throws clause is not the class Throwable (S20.22) or a subclass of Throwable . It is permitted but not required to mention other (unchecked) exceptions in a throws clause.
For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a superclass of that exception type is mentioned in a throws clause in the declaration of the method or constructor.
The requirement to declare checked exceptions allows the compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions will normally result in a compile-time error because of the lack of a proper exception type in a throws clause. Java thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.
The predefined exceptions that are not checked in this way are those for which declaring every possible occurrence would be unimaginably inconvenient:
A method that overrides or hides another method (S8.4.6), including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.
More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. If n has a throws clause that mentions any checked exception types, then m must have a throws clause, and for every checked exception type listed in the throws clause of n, that same exception class or one of its superclasses must occur in the throws clause of m; otherwise, a compile-time error occurs.
See Chapter 11 for more information about exceptions and a large example.
A method body is either a block of code that implements the method or simply a semicolon, indicating the lack of an implementation. The body of a method must be a semicolon if and only if the method is either abstract (S8.4.3.1) or native (S8.4.3.4).
MethodBody: Block ;
A compile-time error occurs if a method declaration is either abstract or native and has a block for its body. A compile-time error occurs if a method declaration is neither abstract nor native and has a semicolon for its body.
If an implementation is to be provided for a method but the implementation requires no executable code, the method body should be written as a block that contains no statements: "{ } ".
If a method is declared void , then its body must not contain any return statement (S14.15) that has an Expression.
If a method is declared to have a return type, then every return statement (S14.15) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (S14.1). In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body."
Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example:
class DizzyDean {
int pitch() { throw new RuntimeException("90 mph?!"); }
}
A class inherits from its direct superclass and direct superinterfaces all the methods (whether abstract
or not) of the superclass and superinterfaces that are accessible to code in the class and are neither overridden (S8.4.6.1) nor hidden (S8.4.6.2) by a declaration in the class.
If a class declares an instance method, then the declaration of that method is said to override any and all methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. Moreover, if the method declared in the class is not abstract , then the declaration of that method is said to implement any and all declarations of abstract methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class.
A compile-time error occurs if an instance method overrides a static method. In this respect, overriding of methods differs from hiding of fields (S8.3), for it is permissible for an instance variable to hide a static variable.
An overridden method can be accessed by using a method invocation expression (S15.11) that contains the keyword super
. Note that a qualified name or a cast to a superclass type is not effective in attempting to access an overridden method; in this respect, overriding of methods differs from hiding of fields. See S15.11.4.10 for discussion and examples of this point.
If a class declares a static method, then the declaration of that method is said to hide any and all methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. A compile-time error occurs if a static method hides an instance method. In this respect, hiding of methods differs from hiding of fields (S8.3), for it is permissible for a static variable to hide an instance variable.
A hidden method can be accessed by using a qualified name or by using a method invocation expression (S15.11) that contains the keyword super
or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields.
If a method declaration overrides or hides the declaration of another method, then a compile-time error occurs if they have different return types or if one has a return type and the other is void . Moreover, a method declaration must not have a throws clause that conflicts (S8.4.4) with that of any method that it overrides or hides; otherwise, a compile-time error occurs. In these respects, overriding of methods differs from hiding of fields (S8.3), for it is permissible for a field to hide a field of another type.
The access modifier (S6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail:
Note that a private
method is never accessible to subclasses and so cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private
method in one of its superclasses, and there is no requirement that the return type or throws
clause of such a method bear any relationship to those of the private
method in the superclass.
It is possible for a class to inherit more than one method with the same signature (S8.4.6.4). Such a situation does not in itself cause a compile-time error. There are then two possible cases:
It is not possible for two or more inherited methods with the same signature not to be abstract , because methods that are not abstract are inherited only from the direct superclass, not from superinterfaces.
There might be several paths by which the same method declaration might be inherited from an interface. This fact causes no difficulty and never, of itself, results in a compile-time error.
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures.
Methods are overridden on a signature-by-signature basis. If, for example, a class declares two public methods with the same name, and a subclass overrides one of them, the subclass still inherits the other method. In this respect, Java differs from C++.
When a method is invoked (S15.11), the number of actual arguments and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (S15.11.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (S15.11.4).
The following examples illustrate some (possibly subtle) points about method declarations.
In the example:
class Point {
int x = 0, y = 0;
void move(int dx, int dy) { x += dx; y += dy; }
}
class SlowPoint extends Point {
int xLimit, yLimit;
void move(int dx, int dy) {
super.move(limit(dx, xLimit), limit(dy, yLimit));
}
static int limit(int d, int limit) {
return d > limit ? limit : d < -limit ? -limit : d;
}
}
the class SlowPoint
overrides the declarations of method move
of class Point
with its own move
method, which limits the distance that the point can move on each invocation of the method. When the move
method is invoked for an instance of class SlowPoint
, the overriding definition in class SlowPoint
will always be called, even if the reference to the SlowPoint
object is taken from a variable whose type is Point
.
In the example:
class Point {
int x = 0, y = 0;
void move(int dx, int dy) { x += dx; y += dy; }
int color;
}
class RealPoint extends Point {
float x = 0.0f, y = 0.0f;
void move(int dx, int dy) { move((float)dx, (float)dy); }
void move(float dx, float dy) { x += dx; y += dy; }
}
the class RealPoint hides the declarations of the int instance variables x and y of class Point with its own float instance variables x and y , and overrides the method move of class Point with its own move method. It also overloads the name move with another method with a different signature (S8.4.2).
In this example, the members of the class RealPoint include the instance variable color inherited from the class Point , the float instance variables x and y declared in RealPoint , and the two move methods declared in RealPoint .
Which of these overloaded move
methods of class RealPoint
will be chosen for any particular method invocation will be determined at compile time by the overloading resolution procedure described in S15.11.
This example is an extended variation of that in the preceding section:
class Point {
int x = 0, y = 0, color;
void move(int dx, int dy) { x += dx; y += dy; }
int getX() { return x; }
int getY() { return y; }
}
class RealPoint extends Point {
float x = 0.0f, y = 0.0f;
void move(int dx, int dy) { move((float)dx, (float)dy); }
void move(float dx, float dy) { x += dx; y += dy; }
float getX() { return x; }
float getY() { return y; }
}
Here the class Point
provides methods getX
and getY
that return the values of its fields x
and y
; the class RealPoint
then overrides these methods by declaring methods with the same signature. The result is two errors at compile time, one for each method, because the return types do not match; the methods in class Point
return values of type int
, but the wanna-be overriding methods in class RealPoint
return values of type float
.
This example corrects the errors of the example in the preceding section:
class Point {
int x = 0, y = 0;
void move(int dx, int dy) { x += dx; y += dy; }
int getX() { return x; }
int getY() { return y; }
int color;
}
class RealPoint extends Point {
float x = 0.0f, y = 0.0f;
void move(int dx, int dy) { move((float)dx, (float)dy); }
void move(float dx, float dy) { x += dx; y += dy; }
int getX() { return (int)Math.floor(x); }
int getY() { return (int)Math.floor(y); }
}
Here the overriding methods getX and getY in class RealPoint have the same return types as the methods of class Point that they override, so this code can be successfully compiled.
Consider, then, this test program:
class Test {
public static void main(String[] args) {
RealPoint rp = new RealPoint();
Point p = rp;
rp.move(1.71828f, 4.14159f);
p.move(1, -1);
show(p.x, p.y);
show(rp.x, rp.y);
show(p.getX(), p.getY());
show(rp.getX(), rp.getY());
}
static void show(int x, int y) {
System.out.println("(" + x + ", " + y + ")");
}
static void show(float x, float y) {
System.out.println("(" + x + ", " + y + ")");
}
}
The output from this program is:
(0, 0) (2.7182798, 3.14159) (2, 3) (2, 3)
The first line of output illustrates the fact that an instance of RealPoint actually contains the two integer fields declared in class Point ; it is just that their names are hidden from code that occurs within the declaration of class RealPoint (and those of any subclasses it might have). When a reference to an instance of class RealPoint in a variable of type Point is used to access the field x , the integer field x declared in class Point is accessed. The fact that its value is zero indicates that the method invocation p.move(1, -1) did not invoke the method move of class Point ; instead, it invoked the overriding method move of class RealPoint .
The second line of output shows that the field access rp.x refers to the field x declared in class RealPoint . This field is of type float , and this second line of output accordingly displays floating-point values. Incidentally, this also illustrates the fact that the method name show is overloaded; the types of the arguments in the method invocation dictate which of the two definitions will be invoked.
The last two lines of output show that the method invocations p.getX()
and rp.getX()
each invoke the getX
method declared in class RealPoint
. Indeed, there is no way to invoke the getX
method of class Point
for an instance of class RealPoint
from outside the body of RealPoint
, no matter what the type of the variable we may use to hold the reference to the object. Thus, we see that fields and methods behave differently: hiding is different from overriding.
A hidden class (static ) method can be invoked by using a reference whose type is the class that actually contains the declaration of the method. In this respect, hiding of static methods is different from overriding of instance methods. The example:
class Super {
static String greeting() { return "Goodnight"; }
String name() { return "Richard"; }
}
class Sub extends Super {
static String greeting() { return "Hello"; }
String name() { return "Dick"; }
}
class Test {
public static void main(String[] args) {
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name());
}
}
produces the output:
Goodnight, Dick
because the invocation of greeting
uses the type of s
, namely Super
, to figure out, at compile time, which class method to invoke, whereas the invocation of name
uses the class of s
, namely Sub
, to figure out, at run time, which instance method to invoke.
Overriding makes it easy for subclasses to extend the behavior of an existing class, as shown in this example:
import java.io.OutputStream; import java.io.IOException;
class BufferOutput {
private OutputStream o;
BufferOutput(OutputStream o) { this.o = o; }
protected byte[] buf = new byte[512];
protected int pos = 0;
public void putchar(char c) throws IOException {
if (pos == buf.length)
flush();
buf[pos++] = (byte)c;
}
public void putstr(String s) throws IOException {
for (int i = 0; i < s.length(); i++)
putchar(s.charAt(i));
}
public void flush() throws IOException {
o.write(buf, 0, pos);
pos = 0;
}
}
class LineBufferOutput extends BufferOutput {
LineBufferOutput(OutputStream o) { super(o); }
public void putchar(char c) throws IOException {
super.putchar(c);
if (c == '\n')
flush();
}
}
class Test {
public static void main(String[] args)
throws IOException
{
LineBufferOutput lbo =
new LineBufferOutput(System.out);
lbo.putstr("lbo\nlbo");
System.out.print("print\n");
lbo.putstr("\n");
}
}
This example produces the output:
lbo print lbo
The class BufferOutput implements a very simple buffered version of an OutputStream , flushing the output when the buffer is full or flush is invoked. The subclass LineBufferOutput declares only a constructor and a single method putchar , which overrides the method putchar of BufferOutput . It inherits the methods putstr and flush from class Buffer .
In the putchar method of a LineBufferOutput object, if the character argument is a newline, then it invokes the flush method. The critical point about overriding in this example is that the method putstr , which is declared in class BufferOutput , invokes the putchar method defined by the current object this , which is not necessarily the putchar method declared in class BufferOutput .
Thus, when putstr is invoked in main using the LineBufferOutput object lbo , the invocation of putchar in the body of the putstr method is an invocation of the putchar of the object lbo , the overriding declaration of putchar that checks for a newline. This allows a subclass of BufferOutput to change the behavior of the putstr method without redefining it.
Documentation for a class such as BufferOutput
, which is designed to be extended, should clearly indicate what is the contract between the class and its subclasses, and should clearly indicate that subclasses may override the putchar
method in this way. The implementor of the BufferOutput
class would not, therefore, want to change the implementation of putstr
in a future implementation of BufferOutput
not to use the method putchar
, because this would break the preexisting contract with subclasses. See the further discussion of binary compatibility in Chapter 13, especially S13.2.
This example uses the usual and conventional form for declaring a new exception type, in its declaration of the class BadPointException :
class BadPointException extends Exception {
BadPointException() { super(); }
BadPointException(String s) { super(s); }
}
class Point {
int x, y;
void move(int dx, int dy) { x += dx; y += dy; }
}
class CheckedPoint extends Point {
void move(int dx, int dy) throws BadPointException {
if ((x + dx) < 0 || (y + dy) < 0)
throw new BadPointException();
x += dx; y += dy;
}
}
This example results in a compile-time error, because the override of method move in class CheckedPoint declares that it will throw a checked exception that the move in class Point has not declared. If this were not considered an error, an invoker of the method move on a reference of type Point could find the contract between it and Point broken if this exception were thrown.
Removing the throws clause does not help:
class CheckedPoint extends Point {
void move(int dx, int dy) {
if ((x + dx) < 0 || (y + dy) < 0)
throw new BadPointException();
x += dx; y += dy;
}
}
A different compile-time error now occurs, because the body of the method move
cannot throw a checked exception, namely BadPointException
, that does not appear in the throws
clause for move
.
| © 1996 Sun Microsystems, Inc. All rights reserved. |