CHAPTER 8
Class declarations define new reference types and describe how they are implemented (§8.1).
The name of a class has as its scope all type declarations in the package in which the class is declared (§8.1.1). A class may be declared abstract
(§8.1.2.1) and must be declared abstract
if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. A class may be declared final
(§8.1.2.2), in which case it cannot have subclasses. If a class is declared public
, then it can be referred to from other packages.
Each class except Object
is an extension of (that is, a subclass of) a single existing class (§8.1.3) and may implement interfaces (§8.1.4).
The body of a class declares members (fields and methods), static initializers, and constructors (§8.1.5). The scope of the name of a member is the entire declaration of the class to which the member belongs. Field, method, and constructor declarations may include the access modifiers (§6.6) public
, protected
, or private
. The members of a class include both declared and inherited members (§8.2). Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.
Field declarations (§8.3) describe class variables, which are incarnated once, and instance variables, which are freshly incarnated for each instance of the class. A field may be declared final
(§8.3.1.2), in which case it cannot be assigned to except as part of its declaration. Any field declaration may include an initializer; the declaration of a final
field must include an initializer.
Method declarations (§8.4) describe code that may be invoked by method invocation expressions (§15.11). A class method is invoked relative to the class type; an instance method is invoked with respect to some particular object that is an instance of the class type. A method whose declaration does not indicate how it is implemented must be declared abstract
. A method may be declared final
(§8.4.3.3), in which case it cannot be hidden or overridden. A method may be implemented by platform-dependent native
code (§8.4.3.4). A synchronized
method (§8.4.3.5) automatically locks an object before executing its body and automatically unlocks the object on return, as if by use of a synchronized
statement (§14.17), thus allowing its activities to be synchronized with those of other threads (§17).
Method names may be overloaded (§8.4.7).
Static initializers (§8.5) are blocks of executable code that may be used to help initialize a class when it is first loaded (§12.4).
Constructors (§8.6) are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded (§8.6.6).
ClassDeclaration:If a class is declared in a named package (§7.4.1) with fully qualified name P (§6.7), then the class has the fully qualified name P
ClassModifiersoptclass
IdentifierSuperopt
Interfacesopt
ClassBody
.
Identifier. If the class is in an
unnamed package (§7.4.2), then the class has the fully qualified name Identifier.
In the example:
class Point { int x, y; }the class
Point
is declared in a compilation unit with no package
statement, and
thus Point
is its fully qualified name, whereas in the example:
package vista; class Point { int x, y; }the fully qualified name of the class
Point
is vista.Point
. (The package name
vista
is suitable for local or personal use; if the package were intended to be
widely distributed, it would be better to give it a unique package name (§7.7).)
A compile-time error occurs if the Identifier naming a class appears as the name of any other class type or interface type declared in the same package (§7.6).
A compile-time error occurs if the Identifier naming a class is also declared as a type by a single-type-import declaration (§7.5.1) in the compilation unit (§7.3) containing the class declaration.
package test;the first compile-time error is caused by the duplicate declaration of the name
import java.util.Vector;
class Point { int x, y; }
interface Point { // compile-time error #1 int getR(); int getTheta(); }
class Vector { Point[] pts; } // compile-time error #2
Point
as both a class
and an interface
in the same package. A second error
detected at compile time is the attempt to declare the name Vector
both by a class
type declaration and by a single-type-import declaration.
Note, however, that it is not an error for the Identifier that names a class also to name a type that otherwise might be imported by a type-import-on-demand declaration (§7.5.2) in the compilation unit (§7.3) containing the class declaration. In the example:
package test;the declaration of the class
import java.util.*;
class Vector { Point[] pts; } // not a compile-time error
Vector
is permitted even though there is also a class
java.util.Vector
. Within this compilation unit, the simple name Vector
refers
to the class test.Vector
, not to java.util.Vector
(which can still be referred
to by code within the compilation unit, but only by its fully qualified name).
package points;
class Point { int x, y; // coordinates PointColor color; // color of this point Point next; // next point with this colordefines two classes that use each other in the declarations of their class members. Because the class type names
static int nPoints; }
class PointColor { Point first; // first point with this color PointColor(int color) { this.color = color; } private int color; // color components }
Point
and PointColor
have the entire package
points
, including the entire current compilation unit, as their scope, this example
compiles correctly-that is, forward reference is not a problem.
ClassModifiers:The access modifier
ClassModifier
ClassModifiersClassModifier ClassModifier: one of
public
abstract final
public
is discussed in §6.6. A compile-time error occurs if
the same modifier appears more than once in a class declaration. If two or more
class modifiers appear in a class declaration, then it is customary, though not
required, that they appear in the order consistent with that shown above in the production
for ClassModifier.
abstract
class is a class that is incomplete, or to be considered incomplete.
Only abstract
classes may have abstract
methods (§8.4.3.1, §9.4), that is,
methods that are declared but not yet implemented. If a class that is not abstract
contains an abstract
method, then a compile-time error occurs. A class has
abstract
methods if any of the following is true:
abstract
method (§8.4.3).
abstract
method from its direct superclass (§8.1.3).
abstract
) and the class neither declares nor inherits a method that implements it.
abstract class Point { int x = 1, y = 1; void move(int dx, int dy) { x += dx; y += dy; alert(); } abstract void alert(); }a class
abstract class ColoredPoint extends Point { int color; }
class SimplePoint extends Point { void alert() { } }
Point
is declared that must be declared abstract
, because it contains a
declaration of an abstract
method named alert
. The subclass of Point
named
ColoredPoint
inherits the abstract
method alert
, so it must also be declared
abstract
. On the other hand, the subclass of Point
named SimplePoint
provides
an implementation of alert
, so it need not be abstract
.
A compile-time error occurs if an attempt is made to create an instance of an abstract
class using a class instance creation expression (§15.8). An attempt to instantiate an abstract
class using the newInstance
method of class Class
(§20.3.6) will cause an InstantiationException
(§11.5.1) to be thrown. Thus, continuing the example just shown, the statement:
Point p = new Point();would result in a compile-time error; the class
Point
cannot be instantiated
because it is abstract
. However, a Point
variable could correctly be initialized
with a reference to any subclass of Point
, and the class SimplePoint
is not
abstract
, so the statement:
Point p = new SimplePoint();would be correct.
A subclass of an abstract
class that is not itself abstract
may be instantiated, resulting in the execution of a constructor for the abstract
class and, therefore, the execution of the field initializers for instance variables of that class. Thus, in the example just given, instantiation of a SimplePoint
causes the default constructor and field initializers for x
and y
of Point
to be executed.
It is a compile-time error to declare an abstract
class type such that it is not possible to create a subclass that implements all of its abstract
methods. This situation can occur if the class would have as members two abstract
methods that have the same method signature (§8.4.2) but different return types. As an example, the declarations:
interface Colorable { void setColor(int color); } abstract class Colored implements Colorable { abstract int setColor(int color); }result in a compile-time error: it would be impossible for any subclass of class
Colored
to provide an implementation of a method named setColor
, taking one
argument of type int
, that can satisfy both abstract
method specifications,
because the one in interface Colorable
requires the same method to return no
value, while the one in class Colored
requires the same method to return a value
of type int
(§8.4).
A class type should be declared abstract
only if the intent is that subclasses can be created to complete the implementation. If the intent is simply to prevent instantiation of a class, the proper way to express this is to declare a constructor (§8.6.8) of no arguments, make it private
, never invoke it, and declare no other constructors. A class of this form usually contains class methods and variables. The class java.lang.Math
is an example of a class that cannot be instantiated; its declaration looks like this:
public final class Math {
private Math() { } // never instantiate this class
. . . declarations of class variables and methods . . .
}
final
if its definition is complete and no subclasses are
desired or required. A compile-time error occurs if the name of a final
class
appears in the extends
clause (§8.1.3) of another class
declaration; this implies
that a final
class cannot have any subclasses. A compile-time error occurs if a
class is declared both final
and abstract
, because the implementation of such a
class could never be completed (§8.1.2.1).
Because a final
class never has any subclasses, the methods of a final
class are never overridden (§8.4.6.1).
extends
clause in a class declaration specifies the direct superclass
of the current class. A class is said to be a direct subclass of the class it extends.
The direct superclass is the class from whose implementation the implementation
of the current class is derived. The extends
clause must not appear in the definition
of the class java.lang.Object
(§20.1), because it is the primordial class
and has no direct superclass. If the class declaration for any other class has no
extends
clause, then the class has the class java.lang.Object
as its implicit
direct superclass.
Super:The following is repeated from §4.3 to make the presentation here clearer:
extends
ClassType
ClassType:The ClassType must name an accessible (§6.6) class type, or a compile-time error occurs. All classes in the current package are accessible. Classes in other packages are accessible if the host system permits access to the package (§7.2) and the class is declared
TypeName
public
. If the specified ClassType names a class that is final
(§8.1.2.2), then a compile-time error occurs; final
classes are not allowed to have subclasses.
the relationships are as follows:
class Point { int x, y; }
final class ColoredPoint extends Point { int color; }
class Colored3DPoint extends ColoredPoint { int z; } // error
Point
is a direct subclass of java.lang.Object
.
java.lang.Object
is the direct superclass of the class Point
.
ColoredPoint
is a direct subclass of class Point
.
Point
is the direct superclass of class ColoredPoint
.
Colored3dPoint
causes a compile-time error because it
attempts to extend the final
class ColoredPoint
.
The subclass relationship is the transitive closure of the direct subclass relationship. A class A is a subclass of class C if either of the following is true:
the relationships are as follows:
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
final class Colored3dPoint extends ColoredPoint { int z; }
Point
is a superclass of class ColoredPoint
.
Point
is a superclass of class Colored3dPoint
.
ColoredPoint
is a subclass of class Point
.
ColoredPoint
is a superclass of class Colored3dPoint
.
Colored3dPoint
is a subclass of class ColoredPoint
.
Colored3dPoint
is a subclass of class Point
.
causes a compile-time error. If circularly declared classes are detected at run time, as classes are loaded (§12.2), then a
class Point extends ColoredPoint { int x, y; }
class ColoredPoint extends Point { int color; }
ClassCircularityError
is thrown.
implements
clause in a class declaration lists the names of interfaces
that are direct superinterfaces of the class being declared:
Interfaces:The following is repeated from §4.3 to make the presentation here clearer:
implements
InterfaceTypeList InterfaceTypeList:
InterfaceType
InterfaceTypeList,
InterfaceType
InterfaceType:Each InterfaceType must name an accessible (§6.6) interface type, or a compile- time error occurs. All interfaces in the current package are accessible. Interfaces in other packages are accessible if the host system permits access to the package (§7.4.4) and the interface is declared
TypeName
public
.
A compile-time error occurs if the same interface is mentioned two or more times in a single implements
clause, even if the interface is named in different ways; for example, the code:
class Redundant implements java.lang.Cloneable, Cloneable { int x; }results in a compile-time error because the names
java.lang.Cloneable
and
Cloneable
refer to the same interface.
An interface type I is a superinterface of class type C if any of the following is true:
public interface Colorable { void setColor(int color); int getColor(); }the relationships are as follows:
public interface Paintable extends Colorable { int MATTE = 0, GLOSSY = 1; void setFinish(int finish); int getFinish(); }
class Point { int x, y; }
class ColoredPoint extends Point implements Colorable { int color; public void setColor(int color) { this.color = color; } public int getColor() { return color; } }
class PaintedPoint extends ColoredPoint implements Paintable
{ int finish; public void setFinish(int finish) { this.finish = finish; } public int getFinish() { return finish; } }
Paintable
is a superinterface of class PaintedPoint
.
Colorable
is a superinterface of class ColoredPoint
and of class PaintedPoint
.
Paintable
is a subinterface of the interface Colorable
, and Colorable
is a superinterface of Paintable
, a
s defined in §9.1.3.
PaintedPoint
has Colorable
as a superinterface both because it is a superinterface
of ColoredPoint
and because it is a superinterface of Paintable
.
Unless the class being declared is abstract
, the declarations of the methods defined in each direct superinterface must be implemented either by a declaration in this class or by an existing method declaration inherited from the direct superclass, because a class that is not abstract
is not permitted to have abstract
methods (§8.1.2.1).
interface Colorable { void setColor(int color); int getColor(); }causes a compile-time error, because
class Point { int x, y; };
class ColoredPoint extends Point implements Colorable { int color; }
ColoredPoint
is not an abstract
class but
it fails to provide an implementation of methods setColor
and getColor
of the
interface Colorable
.
It is permitted for a single method declaration in a class to implement methods of more than one superinterface. For example, in the code:
interface Fish { int getNumberOfScales(); }
interface Piano { int getNumberOfScales(); }
class Tuna implements Fish, Piano { // You can tune a piano, but can you tuna fish? int getNumberOfScales() { return 91; } }the method
getNumberOfScales
in class Tuna
has a name, signature, and return
type that matches the method declared in interface Fish
and also matches the
method declared in interface Piano
; it is considered to implement both.
On the other hand, in a situation such as this:
interface Fish { int getNumberOfScales(); }
interface StringBass { double getNumberOfScales(); }
class Bass implements Fish, StringBass { // This declaration cannot be correct, no matter what type is used. public ??? getNumberOfScales() { return 91; } }it is impossible to declare a method named
getNumberOfScales
with the same
signature and return type as those of both the methods declared in interface Fish
and in interface StringBass
, because a class can have only one method with a
given signature (§8.4). Therefore, it is impossible for a single class to implement
both interface Fish
and interface StringBass
(§8.4.6).
ClassBody:The scope of the name of a member declared in or inherited by a class type is the entire body of the class type declaration.
{
ClassBodyDeclarationsopt}
ClassBodyDeclarations:
ClassBodyDeclaration
ClassBodyDeclarationsClassBodyDeclaration ClassBodyDeclaration:
ClassMemberDeclaration
StaticInitializer
ConstructorDeclaration ClassMemberDeclaration:
FieldDeclaration
MethodDeclaration
Object
, which has no direct superclass
private
are not inherited by subclasses of that class. Only members of a class that are declared protected
or public
are inherited by subclasses declared in a package other than the one in which the class is declared.Constructors and static initializers are not members and therefore are not inherited.
class Point { int x, y; private Point() { reset(); } Point(int x, int y) { this.x = x; this.y = y; } private void reset() { this.x = 0; this.y = 0; } }causes four compile-time errors:
class ColoredPoint extends Point { int color; void clear() { reset(); } // error }
class Test { public static void main(String[] args) { ColoredPoint c = new ColoredPoint(0, 0); // error c.reset(); // error } }
ColoredPoint
has no constructor declared with two integer parameters, as requested by the use in main
. This illustrates the fact that ColoredPoint
does not inherit the constructors of its superclass Point
.
ColoredPoint
declares no constructors, and therefore a default constructor for it is automatically created (§8.6.7), and this default constructor is equivalent to:
ColoredPoint() { super(); }
ColoredPoint
. The error is that the constructor for Point
that takes no arguments is private
, and therefore is not accessible outside the class Point
, even through a superclass constructor invocation (§8.6.5).
reset
of class Point
is private
, and therefore is not inherited by class ColoredPoint
. The method invocations in method clear
of class ColoredPoint
and in method main
of class Test
are therefore not correct.
points
package declares two compilation units:
package points;
public class Point { int x, y;and:
public void move(int dx, int dy) { x += dx; y += dy; } }
package points;
public class Point3d extends Point { int z; public void move(int dx, int dy, int dz) { x += dx; y += dy; z += dz; } }and a third compilation unit, in another package, is:
import points.Point3d;
class Point4d extends Point3d { int w; public void move(int dx, int dy, int dz, int dw) { x += dx; y += dy; z += dz; w += dw; // compile-time errors } }Here both classes in the
points
package compile. The class Point3d
inherits the
fields x
and y
of class Point
, because it is in the same package as Point
. The
class Point4d
, which is in a different package, does not inherit the fields x
and y
of class Point
or the field z
of class Point3d
, and so fails to compile.
A better way to write the third compilation unit would be:
import points.Point3d;
class Point4d extends Point3d { int w; public void move(int dx, int dy, int dz, int dw) { super.move(dx, dy, dz); w += dw; } }using the
move
method of the superclass Point3d
to process dx
, dy
, and dz
. If
Point4d
is written in this way it will compile without errors.
Point
:
package points;
public class Point {the
public int x, y;
protected int useCount = 0;
static protected int totalUseCount = 0;
public void move(int dx, int dy) { x += dx; y += dy; useCount++; totalUseCount++; }
}
public
and protected
fields x
, y
, useCount
and totalUseCount
are inherited
in all subclasses of Point
. Therefore, this test program, in another package,
can be compiled successfully:
class Test extends points.Point { public void moveBack(int dx, int dy) { x -= dx; y -= dy; useCount++; totalUseCount++; } }
class Point {the class variable totalMoves can be used only within the class
int x, y;
void move(int dx, int dy) { x += dx; y += dy; totalMoves++; }
private static int totalMoves;
void printMoves() { System.out.println(totalMoves); }
}
class Point3d extends Point {
int z;
void move(int dx, int dy, int dz) { super.move(dx, dy); z += dz; totalMoves++; }
}
Point
; it is not
inherited by the subclass Point3d
. A compile-time error occurs at the point where
method move
of class Point3d
tries to increment totalMoves.
public
, instances of the class might be
available at run time to code outside the package in which it is declared if it has a
public
superclass or superinterface. An instance of the class can be assigned to a
variable of such a public
type. An invocation of a public
method of the object
referred to by such a variable may invoke a method of the class if it implements or
overrides a method of the public
superclass or superinterface. (In this situation,
the method is necessarily declared public
, even though it is declared in a class
that is not public
.)
Consider the compilation unit:
package points;
public class Point { public int x, y; public void move(int dx, int dy) { x += dx; y += dy; } }and another compilation unit of another package:
package morePoints;
class Point3d extends points.Point { public int z; public void move(int dx, int dy, int dz) { super.move(dx, dy); z += dz; } }An invocation
public class OnePoint { static points.Point getOne() { return new Point3d(); } }
morePoints.OnePoint.getOne()
in yet a third package would
return a Point3d
that can be used as a Point
, even though the type Point3d
is
not available outside the package morePoints
. The method move
could then be
invoked for that object, which is permissible because method move
of Point3d
is
public
(as it must be, for any method that overrides a public
method must itself
be public
, precisely so that situations such as this will work out correctly). The
fields x
and y
of that object could also be accessed from such a third package.
While the field z
of class Point3d
is public
, it is not possible to access this field from code outside the package morePoints
, given only a reference to an instance of class Point3d
in a variable p
of type Point
. This is because the expression p.z
is not correct, as p
has type Point
and class Point
has no field named z
; also, the expression ((Point3d)p).z
is not correct, because the class type Point3d
cannot be referred to outside package morePoints
. The declaration of the field z
as public
is not useless, however. If there were to be, in package morePoints
, a public
subclass Point4d
of the class Point3d
:
package morePoints;
public class Point4d extends Point3d { public int w; public void move(int dx, int dy, int dz, int dw) { super.move(dx, dy, dz); w += dw; } }then class
Point4d
would inherit the field z
, which, being public
, could then be
accessed by code in packages other than morePoints
, through variables and
expressions of the public
type Point4d
.
FieldDeclaration:The FieldModifiers are described in §8.3.1. The Identifier in a FieldDeclarator may be used in a name to refer to the field. The name of a field has as its scope (§6.3) the entire body of the class declaration in which it is declared. More than one field may be declared in a single field declaration by using more than one declarator; the FieldModifiers and Type apply to all the declarators in the declaration. Variable declarations involving array types are discussed in §10.2.
FieldModifiersoptType
VariableDeclarators
;
VariableDeclarators:
VariableDeclarator
VariableDeclarators,
VariableDeclarator VariableDeclarator:
VariableDeclaratorId
VariableDeclaratorId=
VariableInitializer VariableDeclaratorId:
Identifier
VariableDeclaratorId[ ]
VariableInitializer:
Expression
ArrayInitializer
It is a compile-time error for the body of a class declaration to contain declarations of two fields with the same name. Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (§6.5).
If the class declares a field with a certain name, then the declaration of that field is said to hide (§6.3.1) any and all accessible declarations of fields with the same name in the superclasses and superinterfaces of the class.
If a field declaration hides the declaration of another field, the two fields need not have the same type.
A class inherits from its direct superclass and direct superinterfaces all the fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.
It is possible for a class to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.
There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.
A hidden field can be accessed by using a qualified name (if it is static
) or by using a field access expression (§15.10) that contains the keyword super
or a cast to a superclass type. See §15.10.2 for discussion and an example.
FieldModifiers:The access modifiers
FieldModifier
FieldModifiersFieldModifier FieldModifier: one of
public protected private
final static transient volatile
public
, protected
, and private
are discussed in §6.6. A
compile-time error occurs if the same modifier appears more than once in a field
declaration, or if a field declaration has more than one of the access modifiers
public
, protected
, and private
. If two or more (distinct) field modifiers
appear in a field declaration, it is customary, though not required, that they appear
in the order consistent with that shown above in the production for FieldModifier.
static
, there exists exactly one incarnation of the field, no
matter how many instances (possibly zero) of the class may eventually be created.
A static
field, sometimes called a class variable, is incarnated when the class is
initialized (§12.4).
A field that is not declared static
(sometimes called a non-static
field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
class Point { int x, y, useCount; Point(int x, int y) { this.x = x; this.y = y; } final static Point origin = new Point(0, 0); }prints:
class Test { public static void main(String[] args) { Point p = new Point(1,1); Point q = new Point(2,2); p.x = 3; p.y = 3; p.useCount++; p.origin.useCount++; System.out.println("(" + q.x + "," + q.y + ")"); System.out.println(q.useCount); System.out.println(q.origin == Point.origin); System.out.println(q.origin.useCount); } }
(2,2) 0 true 1showing that changing the fields
x
, y
, and useCount
of p
does not affect the fields
of q
, because these fields are instance variables in distinct objects. In this example,
the class variable origin
of the class Point
is referenced both using the class
name as a qualifier, in Point.origin
, and using variables of the class type in
field access expressions (§15.10), as in p.origin
and q.origin
. These two ways
of accessing the origin
class variable access the same object, evidenced by the
fact that the value of the reference equality expression (§15.20.3):
q.origin==Point.origin
is true
. Further evidence is that the incrementation:
p.origin.useCount++;causes the value of q.origin.useCount to be
1
; this is so because p.origin
and
q.origin
refer to the same variable.
final
, in which case its declarator must include a variable
initializer or a compile-time error occurs. Both class and instance variables
(static
and non-static
fields) may be declared final
.
Any attempt to assign to a final
field results in a compile-time error. Therefore, once a final
field has been initialized, it always contains the same value. If a final
field holds a reference to an object, then the state of the object may be changed by operations on the object, but the field will always refer to the same object. This applies also to arrays, because arrays are objects; if a final
field holds a reference to an array, then the components of the array may be changed by operations on the array, but the field will always refer to the same array.
Declaring a field final
can serve as useful documentation that its value will not change, can help to avoid programming errors, and can make it easier for a compiler to generate efficient code.
class Point { int x, y; int useCount; Point(int x, int y) { this.x = x; this.y = y; } final static Point origin = new Point(0, 0); }the class
Point
declares a final
class variable origin
. The origin
variable
holds a reference to an object that is an instance of class Point
whose coordinates
are (0, 0). The value of the variable Point.origin
can never change, so it always
refers to the same Point
object, the one created by its initializer. However, an
operation on this Point
object might change its state-for example, modifying its
useCount
or even, misleadingly, its x
or y
coordinate.
transient
to indicate that they are not part of the persistent
state of an object. If an instance of the class Point
:
class Point { int x, y; transient float rho, theta; }were saved to persistent storage by a system service, then only the fields
x
and y
would be saved. This specification does not yet specify details of such services;
we intend to provide them in a future version of this specification.
Java provides a second mechanism that is more convenient for some purposes: a field may be declared volatile
, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.
If, in the following example, one thread repeatedly calls the method one
(but no more than Integer.MAX_VALUE
(§20.7.2) times in all), and another thread repeatedly calls the method two
:
class Test {then method
static int i = 0, j = 0;
static void one() { i++; j++; } static void two() { System.out.println("i=" + i + " j=" + j); }
}
two
could occasionally print a value for j
that is greater than the
value of i
, because the example includes no synchronization and, under the rules
explained in §17, the shared values of i
and j
might be updated out of order.
One way to prevent this out-or-order behavior would be to declare methods one
and two
to be synchronized
(§8.4.3.5):
class Test {This prevents method
static int i = 0, j = 0;
static synchronized void one() { i++; j++; } static synchronized void two() { System.out.println("i=" + i + " j=" + j); }
}
one
and method two
from being executed concurrently, and
furthermore guarantees that the shared values of i
and j
are both updated before
method one
returns. Therefore method two
never observes a value for j
greater
than that for i
; indeed, it always observes the same value for i
and j
.
Another approach would be to declare i
and j
to be volatile
:
class Test {This allows method
static volatile int i = 0, j = 0;
static void one() { i++; j++; } static void two() { System.out.println("i=" + i + " j=" + j); }
}
one
and method two
to be executed concurrently, but guarantees
that accesses to the shared values for i
and j
occur exactly as many times,
and in exactly the same order, as they appear to occur during execution of the program
text by each thread. Therefore, method two
never observes a value for j
greater than that for i
, because each update to i
must be reflected in the shared
value for i
before the update to j
occurs. It is possible, however, that any given
invocation of method two
might observe a value for j
that is much greater than the
value observed for i
, because method one
might be executed many times between
the moment when method two
fetches the value of i
and the moment when
method two
fetches the value of j
.
See §17 for more discussion and examples.
A compile-time error occurs if a final
variable is also declared volatile
.
static
field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized (§12.4).
static
), then the variable initializer is evaluated and the assignment performed each time an instance of the class is created (§12.5).
class Point { int x = 1, y = 5; }produces the output:
class Test { public static void main(String[] args) { Point p = new Point(); System.out.println(p.x + ", " + p.y); } }
1, 5because the assignments to
x
and y
occur whenever a new Point
is created.
Variable initializers are also used in local variable declaration statements (§14.3), where the initializer is evaluated and the assignment performed each time the local variable declaration statement is executed.
It is a compile-time error if the evaluation of a variable initializer for a field of a class (or interface) can complete abruptly with a checked exception (§11.2).
class Test { static float f = j; // compile-time error: forward reference static int j = 1; static int k = k+1; // compile-time error: forward reference }causes two compile-time errors, because
j
is referred to in the initialization of f
before j
is declared and because the initialization of k
refers to k
itself.
If a reference by simple name to any instance variable occurs in an initialization expression for a class variable, then a compile-time error occurs.
If the keyword this
(§15.7.2) or the keyword super
(§15.10.2, §15.11) occurs in an initialization expression for a class variable, then a compile-time error occurs.
(One subtlety here is that, at run time, static
variables that are final
and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (§9.3.1). These variables are "constants" that will never be observed to have their default initial values (§4.5.4), even by devious programs. See §12.4.2 and §13.4.8 for more discussion.)
class Test { float f = j; int j = 1; int k = k+1; }causes two compile-time errors, because
j
is referred to in the initialization of f
before j
is declared and because the initialization of k
refers to k
itself.
Initialization expressions for instance variables may use the simple name of any static
variable declared in or inherited by the class, even one whose declaration occurs textually later. Thus the example:
class Test { float f = j; static int j = 1; }compiles without error; it initializes
j
to 1
when class Test
is initialized, and initializes
f
to the current value of j
every time an instance of class Test
is created.
Initialization expressions for instance variables are permitted to refer to the current object this
(§15.7.2) and to use the keyword super
(§15.10.2, §15.11).
class Point { static int x = 2; }produces the output:
class Test extends Point { static double x = 4.7; public static void main(String[] args) {
new Test().printX(); } void printX() { System.out.println(x + " " + super.x); } }
4.7 2because the declaration of
x
in class Test
hides the definition of x
in class Point
,
so class Test
does not inherit the field x
from its superclass Point
. Within the
declaration of class Test
, the simple name x
refers to the field declared within
class Test
. Code in class Test
may refer to the field x
of class Point
as super.x
(or, because x
is static
, as Point.x
). If the declaration of Test.x
is deleted:
class Point { static int x = 2; }then the field
class Test extends Point { public static void main(String[] args) { new Test().printX(); } void printX() { System.out.println(x + " " + super.x); } }
x
of class Point
is no longer hidden within class Test
; instead, the
simple name x
now refers to the field Point.x
. Code in class Test
may still refer
to that same field as super.x
. Therefore, the output from this variant program is:
2 2
class Point { int x = 2; }produces the output:
class Test extends Point { double x = 4.7; void printBoth() { System.out.println(x + " " + super.x); } public static void main(String[] args) { Test sample = new Test(); sample.printBoth(); System.out.println(sample.x + " " +
((Point)sample).x); } }
4.7 2 4.7 2because the declaration of
x
in class Test
hides the definition of x
in class Point
,
so class Test
does not inherit the field x
from its superclass Point
. It must be
noted, however, that while the field x
of class Point
is not inherited by class
Test
, it is nevertheless implemented by instances of class Test
. In other words,
every instance of class Test
contains two fields, one of type int
and one of type
float
. Both fields bear the name x
, but within the declaration of class Test
, the
simple name x
always refers to the field declared within class Test
. Code in
instance methods of class Test
may refer to the instance variable x
of class Point
as super.x
.
Code that uses a field access expression to access field x
will access the field named x
in the class indicated by the type of reference expression. Thus, the expression sample.x
accesses a float
value, the instance variable declared in class Test
, because the type of the variable sample is Test
, but the expression ((Point)sample).x
accesses an int
value, the instance variable declared in class Point
, because of the cast to type Point
.
If the declaration of x
is deleted from class Test
, as in the program:
class Point { static int x = 2; }then the field
class Test extends Point { void printBoth() { System.out.println(x + " " + super.x); } public static void main(String[] args) { Test sample = new Test(); sample.printBoth(); System.out.println(sample.x + " " +
((Point)sample).x); } }
x
of class Point
is no longer hidden within class Test
. Within
instance methods in the declaration of class Test
, the simple name x
now refers to
the field declared within class Point
. Code in class Test
may still refer to that
same field as super.x
. The expression sample.x
still refers to the field x
within
type Test
, but that field is now an inherited field, and so refers to the field x
declared in class Point
. The output from this variant program is:
2 2 2 2
super
(§15.10.2) may
be used to access such fields unambiguously. In the example:
interface Frob { float v = 2.0f; }
class SuperTest { int v = 3; }
class Test extends SuperTest implements Frob { public static void main(String[] args) { new Test().printV(); } void printV() { System.out.println(v); } }the class
Test
inherits two fields named v
, one from its superclass SuperTest
and
one from its superinterface Frob
. This in itself is permitted, but a compile-time
error occurs because of the use of the simple name v
in method printV
: it cannot
be determined which v
is intended.
The following variation uses the field access expression super.v
to refer to the field named v
declared in class SuperTest
and uses the qualified name Frob.v
to refer to the field named v
declared in interface Frob
:
interface Frob { float v = 2.0f; }
class SuperTest { int v = 3; }
class Test extends SuperTest implements Frob { public static void main(String[] args) { new Test().printV(); } void printV() { System.out.println((super.v + Frob.v)/2); } }It compiles and prints:
2.5Even if two distinct inherited fields have the same type, the same value, and are both
final
, any reference to either field by simple name is considered ambiguous and results in a compile-time error. In the example:
interface Color { int RED=0, GREEN=1, BLUE=2; }
interface TrafficLight { int RED=0, YELLOW=1, GREEN=2; }
class Test implements Color, TrafficLight { public static void main(String[] args) { System.out.println(GREEN); // compile-time error System.out.println(RED); // compile-time error } }it is not astonishing that the reference to
GREEN
should be considered ambiguous,
because class Test
inherits two different declarations for GREEN
with different
values. The point of this example is that the reference to RED
is also considered
ambiguous, because two distinct declarations are inherited. The fact that the two
fields named RED
happen to have the same type and the same unchanging value
does not affect this judgment.
public interface Colorable { int RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff; }the fields
public interface Paintable extends Colorable { int MATTE = 0, GLOSSY = 1; }
class Point { int x, y; }
class ColoredPoint extends Point implements Colorable { . . . }
class PaintedPoint extends ColoredPoint implements Paintable { . . .RED
. . . }
RED
, GREEN
, and BLUE
are inherited by the class PaintedPoint
both
through its direct superclass ColoredPoint
and through its direct superinterface
Paintable
. The simple names RED
, GREEN
, and BLUE
may nevertheless be used
without ambiguity within the class PaintedPoint
to refer to the fields declared in
interface Colorable
.
MethodDeclaration:The MethodModifiers are described in §8.4.3, the Throws clause in §8.4.4, and the MethodBody in §8.4.5. A method declaration either specifies the type of value that the method returns or uses the keyword
MethodHeaderMethodBody MethodHeader:
MethodModifiersoptResultType
MethodDeclarator
Throwsopt ResultType:
Type
void
MethodDeclarator:
Identifer(
FormalParameterListopt)
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:but should not be used in new Java code.
MethodDeclarator[ ]
It is a compile-time error for the body of a class to have as members two methods with the same signature (§8.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 (§6.5).
FormalParameterList:The following is repeated from §8.3 to make the presentation here clearer:
FormalParameter
FormalParameterList,
FormalParameter FormalParameter:
TypeVariableDeclaratorId
VariableDeclaratorId:If a method has no parameters, only an empty pair of parentheses appears in the method's declaration.
Identifier
VariableDeclaratorId[ ]
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 (§15.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 (§6.6).
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:The access modifiers
MethodModifier
MethodModifiersMethodModifier MethodModifier: one of
public protected private
abstract static final synchronized native
public
, protected
, and private
are discussed in §6.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.
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:
abstract
, and this declaration is inherited by C, thereby providing an implementation of method m that is visible to C.
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 (§18), or to declare that the set of checked exceptions (§11.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); } }The overriding declaration of method
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; }
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
(§20.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 } }
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.
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 (§8.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; } }Here, inlining the method
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); } } }
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.
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; }
synchronized
method acquires a lock (§17.1) before it executes. For a class
(static)
method, the lock associated with the Class
object (§20.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 (§14.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 {defines a class which is designed for concurrent use. Each instance of the class
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; }
}
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 §17 for more discussion of threads and locks.
Throws:A compile-time error occurs if any ClassType mentioned in a
throws
ClassTypeList ClassTypeList:
ClassType
ClassTypeList,
ClassType
throws
clause is not
the class Throwable
(§20.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:
Error
, for example OutOfMemoryError
, are thrown due to a failure in or of the virtual machine. Many of these are the result of linkage failures and can occur at unpredictable points in the execution of a Java program. Sophisticated programs may yet wish to catch and attempt to recover from some of these conditions.
RuntimeException
, for example NullPointerException
, result from runtime integrity checks and are thrown either directly from the Java program or in library routines. It is beyond the scope of the Java language, and perhaps beyond the state of the art, to include sufficient information in the program to reduce to a manageable number the places where these can be proven not to occur.
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 §11 for more information about exceptions and a large example.
abstract
(§8.4.3.1) or native
(§8.4.3.4).
MethodBody:A compile-time error occurs if a method declaration is either
Block
;
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 (§14.15) that has an Expression.
If a method is declared to have a return type, then every return
statement (§14.15) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (§14.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?!"); }
}
abstract
or not) of the superclass and superinterfaces that are
accessible to code in the class and are neither overridden (§8.4.6.1) nor hidden
(§8.4.6.2) by a declaration in the class.
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 (§8.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 (§15.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 §15.11.4.10 for discussion and examples of this point.
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 (§8.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 (§15.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.
void
. Moreover, a method declaration must not have a
throws
clause that conflicts (§8.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 (§8.3), for it is permissible for a field to hide
a field of another type.
The access modifier (§6.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:
public
, then the overriding or hiding method must be public
; otherwise, a compile-time error occurs.
protected
, then the overriding or hiding method must be protected
or public
; otherwise, a compile-time error occurs.
private
; otherwise, a compile-time error occurs.
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.
abstract
, then there are two subcases:
abstract
is static
, a compile-time error occurs.
abstract
is considered to override, and therefore to implement, all the other methods on behalf of the class that inherits it. A compile-time error occurs if, comparing the method that is not abstract
with each of the other of the inherited methods, for any such pair, either they have different return types or one has a return type and the other is void
. Moreover, a compile-time error occurs if the inherited method that is not abstract
has a throws
clause that conflicts (§8.4.4) with that of any other of the inherited methods.
abstract
, then the class is necessarily an abstract
class and is considered to inherit all the abstract
methods. A compile-time error occurs if, for any two such inherited methods, either they have different return types or one has a return type and the other is void
. (The throws
clauses do not cause errors in this case.)
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.
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 (§15.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 (§15.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 (§15.11.4).
class Point {the class
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; }
}
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
.
class Point {the class
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; }
}
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 (§8.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 §15.11.
class Point {Here the class
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; }
}
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
.
class Point {Here the overriding methods
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); }
}
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()); }The output from this program is:
static void show(int x, int y) { System.out.println("(" + x + ", " + y + ")"); }
static void show(float x, float y) { System.out.println("(" + x + ", " + y + ")"); }
}
(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.
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"; } }produces the output:
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()); } }
Goodnight, Dickbecause 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.
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)); }This example produces the output:
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"); } }
lbo print lboThe 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 §13, especially §13.2.
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; } }This example results in a compile-time error, because the override of method
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; } }
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
.
StaticInitializer:It is a compile-time error for a static initializer to be able to complete abruptly (§14.1, §15.5) with a checked exception (§11.2).
static
Block
The static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. This restriction is designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both:
class Z { static int i = j + 2; static int j = 4; }and:
class Z { static { i = j + 2; } static int i, j; static { j = 4; } }result in compile-time errors.
Accesses to class variables by methods are not checked in this way, so:
class Z { static int peek() { return j; }produces the output:
static int i = peek(); static int j = 1; }
class Test { public static void main(String[] args) { System.out.println(Z.i); }
}
0because the variable initializer for
i
uses the class method peek
to access the
value of the variable j
before j
has been initialized by its variable initializer, at
which point it still has its default value (§4.5.4).
If a return
statement (§14.15) appears anywhere within a static initializer, then a compile-time error occurs.
If the keyword this
(§15.7.2) or the keyword super
(§15.10, §15.11) appears anywhere within a static initializer, then a compile-time error occurs.
ConstructorDeclaration:The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration; otherwise a compile-time error occurs. In all other respects, the constructor declaration looks just like a method declaration that has no result type.
ConstructorModifiersoptConstructorDeclarator
ThrowsoptConstructorBody ConstructorDeclarator:
SimpleTypeName
(
FormalParameterListopt)
class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } }Constructors are invoked by class instance creation expressions (§15.8), by the
newInstance
method of class Class
(§20.3), by the conversions and concatenations caused by the string concatenation operator + (§15.17.1), and by explicit constructor invocations from other constructors (§8.6.5). Constructors are never invoked by method invocation expressions (§15.11). Access to constructors is governed by access modifiers (§6.6). This is useful, for example, in preventing instantiation by declaring an inaccessible constructor (§8.6.8).
Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.
ConstructorModifiers:The access modifiers
ConstructorModifier
ConstructorModifiersConstructorModifier ConstructorModifier: one of
public protected private
public
, protected
, and private
are discussed in §6.6.
A compile-time error occurs if the same modifier appears more than once in a
constructor declaration, or if a constructor declaration has more than one of the
access modifiers public
, protected
, and private
.
Unlike methods, a constructor cannot be abstract
, static
, final
, native
, or synchronized
. A constructor is not inherited, so there is no need to declare it final
and an abstract
constructor could never be implemented. A constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static
. There is no practical need for a constructor to be synchronized
, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work. The lack of native
constructors is an arbitrary language design choice that makes it easy for an implementation of the Java Virtual Machine to verify that superclass constructors are always properly invoked during object creation.
throws
clause for a constructor is identical in structure and behavior to the
throws
clause for a method (§8.4.4).
this
followed by a parenthesized argument
list, or an explicit invocation of a constructor of the direct superclass, written
as super
followed by a parenthesized argument list.
ConstructorBody:It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving
{
ExplicitConstructorInvocationoptBlockStatementsopt
}
ExplicitConstructorInvocation:
this (
ArgumentListopt) ;
ArgumentListopt
super () ;
this
.
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object
, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();
", an invocation of the constructor of its direct superclass that takes no arguments.
Except for the possibility of explicit constructor invocations, the body of a constructor is like the body of a method (§8.4.5). A return
statement (§14.15) may be used in the body of a constructor if it does not include an expression.
class Point {the first constructor of
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}
class ColoredPoint extends Point {
static final int WHITE = 0, BLACK = 1;
int color;
ColoredPoint(int x, int y) { this(x, y, WHITE); }
ColoredPoint(int x, int y, int color) { super(x, y);
this.color = color;
}
}
ColoredPoint
invokes the second, providing an additional
argument; the second constructor of ColoredPoint
invokes the constructor of its
superclass Point
, passing along the coordinates.
An explicit constructor invocation statement may not refer to any instance variables or instance methods declared in this class or any superclass, or use this
or super
in any expression; otherwise, a compile-time error occurs. For example, if the first constructor of ColoredPoint
in the example above were changed to:
ColoredPoint(int x, int y) { this(x, y, color); }then a compile-time error would occur, because an instance variable cannot be used within a superclass constructor invocation.
An invocation of the constructor of the direct superclass, whether it actually appears as an explicit constructor invocation statement or is provided automatically (§8.6.7), performs an additional implicit action after a normal return of control from the constructor: all instance variables that have initializers are initialized at that time, in the textual order in which they appear in the class declaration. An invocation of another constructor in the same class using the keyword this
does not perform this additional implicit action.
§12.5 describes the creation and initialization of new class instances.
Object
, then the default constructor has an empty body.
If the class is declared public
, then the default constructor is implicitly given the access modifier public
(§6.6); otherwise, the default constructor has the default access implied by no access modifier. Thus, the example:
public class Point { int x, y; }is equivalent to the declaration:
public class Point { int x, y; public Point() { super(); } }where the default constructor is
public
because the class Point
is public
.
private
. A
public
class can likewise prevent the creation of instances outside its package by
declaring at least one constructor, to prevent creation of a default constructor with
public
access, and declaring no constructor that is public
.
class ClassOnly { private ClassOnly() { } static String just = "only the lonely"; }the class
ClassOnly
cannot be instantiated, while in the example:
package just;
public class PackageOnly { PackageOnly() { } String[] justDesserts = { "cheesecake", "ice cream" }; }the class
PackageOnly
can be instantiated only within the package just
, in
which it is declared.
Contents | Prev | Next | Index
Java Language Specification (HTML generated by Suzette Pelouch on February 24, 1998)
Copyright © 1996 Sun Microsystems, Inc.
All rights reserved
Please send any comments or corrections to doug.kramer@sun.com