Java - Abstract Classes and Methods

What are Abstract Classes?

Abstract Classes represent a concept rather than to represent objects.

Syntax

You need to use the abstract keyword in the class declaration to declare an abstract class.

For example, the following code declares a Shape class abstract:

abstract class Shape {
        // No code for now
}

Because the Shape class is abstract, you cannot create its object even though it has a public constructor added by compiler.

You can declare a variable of an abstract class as you do for a concrete class.

Shape s;     // OK
new Shape(); // An error. Cannot create a Shape object

Abstract methods

If a method is incomplete, indicate it by using the abstract keyword in the method's declaration.

Shape class looks as follows with an abstract draw() method:

abstract class Shape {
        public Shape() {
        }

        public abstract void draw();
}

An abstract class may have all concrete methods. It may have all abstract methods. It may have some concrete and some abstract methods.

If a class has an abstract method either declared or inherited, it must be declared abstract.

Rule

Abstract class must be subclassed to be useful and the subclass should implement the abstract methods.

A class may be declared abstract even if it does not have an abstract method.

A class must be declared abstract if it declares or inherits an abstract method.

You cannot create an object of an abstract class. However, you can declare a variable of the abstract class type and call methods using it.

An abstract class cannot be declared final.

An abstract class should not declare all constructors private.

An abstract method cannot be declared static.

An abstract method cannot be declared private.

An abstract method in a class can override an abstract method in its superclass without providing an implementation.

The subclass abstract method may refine the return type or exception list of the overridden abstract method.

A concrete instance method may be overridden by an abstract instance method.

Quiz

Example