Skip to content

Abstract Classes

A subclass inherits the methods of its superclass and can choose which methods to override.

public class Light {
  public void changeBulb() {
    // subclasses should override this method
  }
}
class HalogenLight1 extends Light {
  // no override.
}

The abstract modifier declares a class as an abstract class.

public abstract class AbstractLight {
  // subclasses MUST implement this method
  public abstract void changeBulb();
}
  • An abstract class cannot directly be instantiated.

Light light = new Light();                  // Just fine.
AbstractLight alight = new AbstractLight(); // WILL NOT COMPILE
                                            // Cannot instantiate the type AbstractLight
* A non-abstract class - a class that can be directly instantiated with new - is called a concrete class.

  • The order of modifiers in a class declaration is irrelevant.
abstract public class AbstractLight { /*...*/ }

Concrete subclasses of an abstract class must implement (provide code for) its abstract methods.

public class HalogenLight2 extends AbstractLight {
  @Override
  public void changeBulb() {
    System.out.println("Change bulb in halogen light");
    System.out.println("Don't touch the bulb with your bare hands");
  }
}
public class FlourescentLight extends AbstractLight {
  @Override
  public void changeBulb() {
    System.out.println("Change tube in fluorescent lamp.");
    System.out.println("Dispose of old tube properly.");
  }
}
public class LEDLight extends AbstractLight {
  // WILL NOT COMPILE
  // The type LEDLight must implement the inherited abstract method AbstractLight.changeBulb()
}

In UML, the abstract class's name is in italics.

Abstract Light Diagram

The purpose of an abstract class is to be extended.

  • A class can be declared either abstract or final, not both.

Practice Exercise

A concrete subclass is one that has an implementation for all inherited abstract methods (from an abstract superclass or an interface).

This does not mean it has its own implementation of every inherited abstract method. A method could be implemented in a superclass, and the concrete class inherits that implementation.


Prev -- Up -- Next