Java Reference
In-Depth Information
To cater to this, Java has
abstract classes
. An abstract class is a class in which one or more methods are
declared, but not defined. The bodies of these methods are omitted, because, as in the case of the method
sound()
in the
Animal
class, implementing the methods does not make sense. Because they have no defin-
ition and cannot be executed, they are called
abstract methods
. The declaration for an abstract method ends
with a semicolon and you specify the method with the keyword
abstract
to identify it as such. To declare
that a class is abstract you just use the keyword
abstract
in front of the
class
keyword in the first line of
the class definition.
You could have defined the class
Animal
as an abstract class by amending it as follows:
public abstract class Animal {
public abstract void sound();
// Abstract method
public Animal(String aType) {
type = new String(aType);
}
public String toString() {
return "This is a " + type;
}
private String type;
}
The previous program works just as well with these changes. It doesn't matter whether you prefix the
class name with
public abstract
or
abstract public
; they are equivalent, but you should be consistent
in your usage. The sequence
public abstract
is typically preferred. The same goes for the declaration
of an abstract method, but both
public
and
abstract
must precede the return type specification, which is
void
in this case.
An
abstract
method cannot be
private
because a
private
method cannot be inherited and therefore
cannot be redefined in a subclass.
You cannot instantiate an object of an abstract class, but you can declare a variable of an abstract class
type. With the new abstract version of the class
Animal
, you can still write:
Animal thePet = null; // Declare a variable of type Animal
just as you did in the
TryPolymorphism
class. You can then use this variable to store objects of the sub-
classes,
Dog
,
Spaniel
,
Duck
, and
Cat
.
When you derive a class from an abstract base class, you don't have to define all the abstract methods
in the subclass. In this case the subclass is also abstract and you aren't able to instantiate any objects of the
subclass either. If a class is abstract, you must use the
abstract
keyword when you define it, even if it only
inherits an abstract method from its superclass. Sooner or later you must have a subclass that contains no
abstract methods. You can then create objects of this class type.
THE UNIVERSAL SUPERCLASS
I must now reveal something I have been keeping from you.
All
the classes that you define are subclasses by
default — whether you like it or not. All your classes have a standard class,
Object
, as a base, so
Object