Abstract Classes

Abstract Class

Abstract Class is a class that can contain one or more abstract methods.

Instancing abstract class which contains abstract method results in exception.

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

Imports:

In order to use abstract class and abstract methods the following modules need to be imported:

Syntax:

The syntax for defining abstract class is:

Abstract methods

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

If child class does not implement the abstract methods from the parent class, then instancing the child class causes exception.

Example:

Output:

Explanation:

  • At lines 6 - 7 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 will result in exception.
  • At lines 12 - 13 and lines 19 - 20 the abstract method is implemented.
  • If we uncomment line 30, then the code will result in exception. That's because an abstract class containing abstract method cannot be instanced.