Main Page

Previous Next

Abstract Classes

In the class Animal, we introduced a version of the method sound() that did nothing because we wanted to call the sound() method in the subclass objects dynamically. The method sound() has no meaning in the context of the generic class Animal, so implementing it does not make much sense. This situation often arises in object-oriented programming. You will often find yourself creating a superclass from which you will derive a number of subclasses, just to take advantage of polymorphism.

To cater for 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 our class Animal, implementing the methods does not make sense. Since they have no definition and cannot be executed, they are called abstract methods. The declaration for an abstract method ends with a semi-colon and you specify the method with the keyword abstract to identify it as such. To define an abstract class you use the keyword abstract in front of the class name.

We 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 will work 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 since 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 our new abstract version of the class Animal, we can still write:

Animal thePet;    // Declare a variable of type Animal 

just as we did in the TryPolymorphism class. We can then use this variable to store objects of the subclasses, 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 will also be abstract and you won't be 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.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor