Prev Next

Abstract Class

Loosely stated, abstract class falls between a class and interface.

An abstract class may have some methods that are not implemented and others that may be implemented. Non-implemented methods should be specified using 'abstract' keyword.

Since at least one method is not fully implemented, an abstract class can't be instantiated. However, you can declare fields that are not static and final, and define public, protected, and private concrete methods.

Any class extending an abstract class must implement the non-implemented methods. An example below:

    public abstract class A {
        public void a() {          // is implemented
           // body of the method
        }

        public abstract void b();  // not implemented
    }

You can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces. Consider using abstract classes if any of these statements apply to your situation:

  • You want to share code among several closely related classes.
  • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

We noted that a class that implements an interface must implement all of the interface's methods.

It is possible, however, to define a class that does not implement all of the interface's methods, provided that the class is declared to be abstract. For example,

abstract class X implements Y {
  // implements all but one method of Y
}

class XX extends X {
  // implements the remaining method in Y
}

In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y.