Sometimes you want to create classes that provide a structure without necessarily having complete implementations of your methods.

Abstract classes are super classes that provide generalizations that get shared by all its subclasses.

It is then the responsibility of each subclass to provide complete implementations. Abstract classes provide structure or abstraction.

However, unlike interfaces, abstract classes can have both concrete and abstract methods. Normally interfaces only provide abstract methods alone. However, abstract methods can provide implementation for some methods as well.

Any class that has atleast one abstract method must be declated abstract.

An abstract class influences the nature of the methods to be implemented by its children.

They are normally very useful especially when in you are creating a class that has no meaningful implementation of a method. Yet in the context of its subclasses, a meaningful implementation can be provided. Normally these methods need to be overriden to provide this implementation.

If you want a method in a super class to be overriden by its children, then you prefix it with the abstract type modifier.

Abstract methods can also be called subclasser responsibility methods. This is because they have no concrete implementation in the super class. It is the responsibility of the subclasses to implement them.

Abstract Method Syntax

Here’s the syntax of an abstract method.

 abstract type name(parameterList);

Take note that abstract methods don’t have a body.

Creating Abstract class

A class has to be declared abstract provided it has at least one abstract method.

We prefix our class with the abstract keyword to create an abstract class.

 abstract class Galaxy{}

Here are some the things to keep in mind with regard to abstract classes:

  • Any class with one or more abstract method must be declared abstact.
  • Together with abstract methods, an abstract class can have any number of concrete methods with implementations.
  • An abstract class cannot be instantiated directly with the new operator.
  • You can neither make an abstract constructor nor an abstract static method.
  • An abstract class sub-class must either implement all the abstract methods defined in the super class or be declared abstract.
  • Even though we can’t instantiate abstract classes, we can use them to create object references. This is possible since polymorphism is impemented in the JVM through superclass references. We can therefore create a reference to an abstract class and use it to point to a subclass.

Categorized in: