In this post, you will learn to:

  • State the use of abstract methods.
  • Explain the purpose of abstract classes.

‘abstract’ Methods

When a method has only declaration and no implementation, that is, no statements in the body, then it is called an abstract. An abstract method in Java is prefixed with the abstract keyword. An abstract method is only a contract that the subclass will provide its implementation. An abstract method does not specify any implementation. The method declaration does not contain any braces and is terminated by a semicolon.

The following is the syntax for declaring abstract methods.

abstract <method return type> <methodname>([parameter list]);

The following code demonstrates the declaration of abstract method.

public abstract void DraftMemo();

Here, DraftMemo() is an abstract method. As can be seen, the abstract keyword is used to declare the method as abstract. The method declaration is terminated with a semicolon.

‘abstract’ Classes

A class may be required to serve as a framework that provides certain behavior for other classes. A subclass provides their application or requirement-specific behavior that adds to the behavior of the existing framework. Such, a framework is created by using the abstract keyword. Abstract classes cannot be instantiated but can be inherited. The subclass must implement abstract methods declared in base class, otherwise it must be declared as abstract.

The following is the syntax for declaring class as abstract.

abstract class  {

[abstract <method return type> <methodname> ();]
. . .
}

The following code demonstrates the declaration of abstract class.

abstract class OutlineProposal {

   public abstract void DraftMemo();
   public void CalcCosts(){
      System.out.println("Costs");
   }
}

As shown in the code, OutlineProposal is an abstract class. It defines a framework for other classes deriving from it to follow. DraftMemo() is an abstract method declared in the class, OutlineProposal. The implementation of this method varies for each subclass derived from the class, OutlineProposal.