8.1.2
Class Modifiers
CLASSES
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 instanti
ated, resulting in the execution of a constructor for the
abstract
class and, there
fore, 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 con
structor 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 . . .
}
132
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved