Abstract Classes

Abstract Class

Abstract Class is a class that can't be instantiated (objects cannot be created) and may contain abstract methods.

It's supposed to represent something abstract and not specific.

Syntax:

Basic Example

Let's look at the following example:

Output:

Explanation

  • The abstract class Vehicle is defined at lines 1-7.
  • The name of the abstract class is Vehicle. This is something indefinite and it's inherited by other classes.
  • If we uncomment line 25 the code won't compile. That's because an abstract class cannot be instanced.

Abstract methods

Abstract methods can be defined only in abstract classes and have no body.

An abstract method in parent class must be overwritten in the child class.

Syntax:

Example:

Output:

Explanation:

  • At line 3 the abstract method calcArea is defined.
  • Since calcArea is an abstract method, classes that inherit the abstract class Figure must implement the method. If not done then the code won't compile.
  • At lines 19 - 22 and lines 39 - 42 the abstract method is implemented.