Java Reference
In-Depth Information
definition followed by a semicolon. 2 Here are the rules about abstract methods
and the abstract classes that contain them:
• Any class with an abstract method is automatically abstract itself and must
be declared as such. To fail to do so is a compilation error.
• An abstract class cannot be instantiated.
• A subclass of an abstract class can be instantiated only if it overrides each of
the abstract methods of its superclass and provides an implementation (i.e., a
method body) for all of them. Such a class is often called a concrete subclass, to
emphasize the fact that it is not abstract .
• If a subclass of an abstract class does not implement all the abstract methods
it inherits, that subclass is itself abstract and must be declared as such.
static , private , and final methods cannot be abstract , because these types
of methods cannot be overridden by a subclass. Similarly, a final class cannot
contain any abstract methods.
• A class can be declared abstract even if it does not actually have any abstract
methods. Declaring such a class abstract indicates that the implementation is
somehow incomplete and is meant to serve as a superclass for one or more
subclasses that complete the implementation. Such a class cannot be
The Classloader class that we will meet in Chapter 11 is a
good example of an abstract class that does not have any
abstract methods.
Let's look at an example of how these rules work. If we define the Shape class to have
abstract area() and circumference() methods, any subclass of Shape is required
to provide implementations of these methods so that it can be instantiated. In other
words, every Shape object is guaranteed to have implementations of these methods
defined. Example 3-5 shows how this might work. It defines an abstract Shape
class and two concrete subclasses of it.
Example 3-5. An abstract class and concrete subclasses
public abstract class Shape {
public abstract double area (); // Abstract methods: note
public abstract double circumference (); // semicolon instead of body.
2 An abstract method in Java is something like a pure virtual function in C++ (i.e., a virtual func‐
tion that is declared = 0 ). In C++, a class that contains a pure virtual function is called an abstract
class and cannot be instantiated. The same is true of Java classes that contain abstract methods.
Search WWH ::

Custom Search