Abstract class and method in Java

Beginners Code Computer Skills Data Java

In this article, we will see what is an abstraction in Java and what the abstract class and method in java mean.

What is Abstraction in Java?

  • Abstraction is the concept of hiding the implementation details and showing only essential functionalities to the user.
  • It shows only important things to the user and hides the internal details.
  • It emphasizes on outside view of the objects and what the object does instead of how it does it.
  • Abstraction in Java can be categorized as:
    • Abstract class (0 to 100%)
    • Interface (100%)

Abstract class and method in Java:

Abstract classes:

  • If a class is declared with the abstract keyword, then it is known as an abstract class.
  • Basically, the abstract class is used to declare the common characteristics of subclasses.
  • An abstract class cannot be instantiated.
  • It only defines the data fields and methods. But the method implementation is typically not provided.
  • However, an abstract class can also implement some of the methods defined thereby providing a partial implementation of the behavior of the class.

Abstract methods:

  • Methods that do not have their implementation within their definitions are abstract methods.
  • A programmer can derive from the abstract class and then provide the implementation of the methods.
  • It is compulsory to keep an abstract method inside an abstract class.
  • Abstract classes indicate to the compiler that method has been declared in superclass but is designed in the subclass.
  • A programmer deriving a subclass from an abstract class must provide an implementation for all the abstract methods. Otherwise, this subclass will remain an abstract class in the hierarchy.

Why do we need abstract classes?

  • In object-oriented problem solving, there are some occasions when we want to model an abstract concept rather than a physical thing.
  • For example,
    • if we model a physical thing like a Triangle or a Bike, we can instantiate objects, obtain their behavior and solve problems.
    • However, sometimes we may want to create an abstract entity like Number, Shape or Vehicle.
    • Moreover, it would be quite meaningless to be able to instantiate a generic object like a number or shape since the generic behavior of these objects does not mean much.
    • However, we can derive an Integer class from Number, we can derive classes Triangle, Quadrilateral from Shape or a class Bike from Vehicle.
    • Objects instantiated from these classes like Triangle, Quadrilateral, Integer or Bike can provide specific behavior.

Declaration and Use of Abstract class & method in Java:

The general way of declaring an abstract method is:

abstract return_type method_Name(list_of_arguments);

abstract class<Class_Name> {
    
}

Of course, in the abstract Shape class, we can provide an implementation for a method that is generic enough for all shapes. We can also define some abstract methods like this:

abstract double perimeter();

abstract double area();

 Rules for Abstract class & Methods:

  • An abstract class can have zero or more abstract methods.
    • It can provide an implementation for all the methods defined in it.
  • An abstract class can have data members, abstract methods, a method body, constructors and even the main() method.
  • It is compulsory to keep an abstract method inside an abstract class. To clarify, if there are any abstract methods in a class, that class must be declared as abstract.
  • If you are extending an abstract class that has an abstract method, you must either provide the implementation of the method or make this class abstract.

Here is on example for abstract classes and their implementation!

public abstract class Shape {
  
  abstract double perimeter();
  abstract double area();
  
}
import java.util.*;
public class Triangle extends Shape{
  
  double side1;	
    double side2;
    double side3;
    
    public Triangle(double s1, double s2, double s3) {
    	side1 = s1;
    	side2 = s2;
    	side3 = s3;
   	}
  
        
  double perimeter() {
     
      return (side1+side2+side3);		
  }
  
  double area() {
     double semiPerimeter = (side1 + side2 + side3)/2;
     double temp = (semiPerimeter * (semiPerimeter - side1) * (semiPerimeter - side2) * (semiPerimeter - side3));
     double area = Math.sqrt(temp);
     
     return area;
    
  }
   public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter the sides of the Triangle");
     
     double side1=sc.nextInt();
     double side2=sc.nextInt();
     double side3=sc.nextInt();
     Triangle obj = new Triangle(side1, side2, side3);
        
    System.out.println("Perimeter of Triangle: " + (obj.perimeter()));
    System.out.println("Area of Triangle: " + (obj.area()));
  }
}

Output:

Triangle abstract

import java.util.*;
public class Square {
  double side1;	   
    
    public Square(double s1) {
    	side1 = s1;
    }
  
  	double perimeter() { 
      return (4 * side1);		
  }
  
  double area() {
    return (side1 * side1);
  }
   public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter the sides of the Square");
     double side1=sc.nextInt();
       
    Square obj = new Square(side1);
    
    System.out.println("Perimeter of Square: " + (obj.perimeter()));
    System.out.println("Area of Square: " + (obj.area()));
  }
}

Output:

square polymorphism

So what do we learn from this?

  • We cannot instantiate Shape.
  • We can instantiate the Triangle and Square.
  • In class Shape, there is no implementation of abstract double perimeter() and abstract double area() but the classes Triangle and Square take care of this by providing their implementations.

How Abstract class helps in implementing polymorphism?

While we cannot instantiate an abstract class, we can always have a reference to an abstract class. This means that we can have a superclass reference (which could be an abstract class). This enables the implementation of polymorphism.

Look at the below example!

public abstract class Polygon {

  double dimension1;
  double dimension2;
  
  public Polygon(double x, double y) {
    dimension1 = x;
    dimension2 = y;
  }
  
  abstract double perimeter();
  abstract double area();	
}
public class Rectangle extends Polygon {
  
  public Rectangle(double length, double breadth) {
    
    super(length, breadth);
    //super() is used to invoke immediate parent class constructor
  }

  double perimeter() {
     
    return (2 * (dimension1 + dimension2));		
  }

  double area() {
    return (dimension1 * dimension2);
  
  }
  
  public static void main(String[] args) {
    
    Polygon mypolygon = new Rectangle(6, 15);		
    System.out.println("Area of Rectangle = " + mypolygon.area());
    System.out.println("Perimeter of Rectangle = " + mypolygon.perimeter());
    
  }
}

Output:

rectangle polymorphism abstract

public class Circle extends Polygon{	
  
  public Circle(double radius) {
    
    super(radius, radius);	
    // super() is used to invoke immediate parent class constructor
  }

  double perimeter() {
     
    return (2 * 3.14 * dimension1);		
  }

  double area() {
    return (3.14 * dimension1 * dimension2);
  
  }
  
  public static void main(String[] args) {
    
    Polygon mypolygon = new Circle(5);
    System.out.println("Area of Circle = " + mypolygon.area());
    System.out.println("Perimeter of Circle = " + mypolygon.perimeter());
    
  }
}

Output:

circle polymorphism abstract

Computation of area or perimeter is useful and important for all the shapes such as circles, rectangle, squares. But here class polygon is generic and with just two dimensions, it is not definable.

When the classes Circle and Rectangle are derived, the behavior of the methods abstract double perimeter() and abstract double area() can be implemented. Note that we have not instantiated an object mypolygon. It is merely a reference to the abstract class Polygon.

This enables us to implement methods abstract double perimeter() and abstract double area() that are overridden methods and resolved at runtime using mypolygon (the superclass reference variable). Thus abstract double perimeter() and abstract double area() and such methods exhibit polymorphic behavior.

Example of an abstract class having a constructor.

public abstract class Games {
  
  String category = "outdoor game";
  
  Games(){
    System.out.println("Game constructor is invoked");
  }
  
  void playingEnvironment() {
    System.out.println("It is played in a field!");
  }
  
  abstract void playingEquipment();
}

public class Cricket extends Games {
  
   void playingEquipment() {
     System.out.println("\n Important Equipments required for Cricket are ball, bat , stumps, bails ");
   }

   public static void main(String[] args) {
    Games obj = new Cricket();
    obj.playingEquipment();
    obj.playingEnvironment();
    System.out.println("Category is: " + obj.category);
  }
}

Output:

Constructor game polymorphism abstract

Objective: Write a Java program for computing sum of two integers and floats using abstract classes.

public abstract class SumOperator {
  
  abstract void sum();
}
public class IntegerSum extends SumOperator {
  void sum() {
    int a, b, c;
    a = 10;
    b = 20;
    c = a + b;
    System.out.println("INT SUM VALUE = "+ c);
  }

}
public class FloatSum extends SumOperator {
  void sum() {
    float f, g, h;
    f = 10;
    g = 20;
    h = f + g;
    System.out.println("FLOAT SUM VALUE = " + h);
  }
}
public class SumDemo {

  public static void main(String[] args) {
    // SumOperator ob = new SumOperator(); 
    // invalid - cannot instantiate abstract class
    
    SumOperator obj1 = new IntegerSum();
    obj1.sum();
    
    SumOperator obj2 = new FloatSum();
    obj2.sum();
        
  }
}

Output:

abstract INT FLOAT

In the next article, I will explain about Interfaces and their use in Java.