Abstract Methods#

Sometimes a class has a characteristic but that characteristic cannot be described at the current level - it must be described at a lower level, in a subclass. Abstract methods are used to force this.

For example, suppose we add the class Shape to our code from the previous sections. Every shape has an area, but it requires a different calculation depending on which shape. Nevertheless, we want to ensure that calcArea() is defined in all subclasses, and we want it to have a particular signature, namely a specific name and no parameters, and to return a double. The solution is to add an abstract method to the Shape class. If a class contains an abstract method, then it is itself, declared as abstract because no objects should be created of that type.

public abstract class Shape {
   //...other parts of the class
   
   public abstract double calcArea();
}

Now if Circle is a subclass of Shape, then Circle must define calcArea(). The compiler will give an error if that is not done.

public class Circle extends Shape {
   private double radius;
   
   public Circle(double radius){
      this.radius = radius;
   }
}
|   public class Circle extends Shape {
|      private double radius;
|      
|      public Circle(double radius){
|         this.radius = radius;
|      }
|   }
Circle is not abstract and does not override abstract method calcArea() in Shape

This compile-time error is fixed by defining the method calcArea():

public class Circle extends Shape {
   private double radius;
   
   public Circle(double radius){
      this.radius = radius;
   }

   public double calcArea(){
      return Math.PI * radius * radius;
   }
}



Abstract

A class is abstract if no object may be instantiated of that data type. A method is abstract if it must be defined in all immediate subclasses. If a class contains an abstract method, then the class itself must be abstract.