Abstract Class and Methods in Java

Abstract Class and Methods in Java
Abstract Class and Methods in Java

Introduction

Remember this diagram from our biology book in school?

It shows us how light passes through our eyes, enabling us to see. 

But now, as we’re reading this article, we aren’t bothered about how we’re reading it, are we?

Class_Gif
Source: giphy

A similar concept is used in object-oriented programming, called abstraction, where we only use a class without worrying about how it’s working. 

Implementation Of abstraction in two ways:

  1. By using abstract classes
  2. By using an abstract data type called interfaces

In this article, we will learn about an abstract class and methods associated with it (known as abstract methods). 

What is an abstract class and methods?

We just read that abstract classes are used to hide the implementation and only use the functionality. Therefore, an abstract class can be defined as follows:

A class that contains abstract and/or non-abstract methods and is declared using the “abstract” keyword is called an abstract class.

Other than that, some essential points to keep in mind about abstract classes are:

  • They cannot be instantiated, i.e., we cannot create an object of an abstract class.
  • They may have a constructor and static and final methods.

We have been referring to the term “abstract methods” a lot, so you may be wondering what it is.

A method that has no body and is declared as abstract is known as an abstract method. 

blog banner 1

Now that we know what an abstract class and methods are let us see how we create them.

Creating an Abstract Class and Methods

In defining an abstract class and methods, we saw that declaring them using the “abstract ” keyword is necessary. But what is the exact syntax for that?

The syntax to declare an abstract class is:

abstract class Class_name
{
    .....
}

And, the syntax to declare abstract methods is as follows:

abstract return_type function_name( );

Note that the abstract method has no body as mentioned in the definition.

We are well equipped with the basics of an abstract class and methods, so it is time for us to see how they are practically used. 

Practical Use of an Abstract Class and Methods

We have read that abstract classes contain abstract methods, but those methods do not have any functional body. Also, we cannot create objects of an abstract class. Thus, an abstract class and methods cannot be used directly and seem pretty useless at first. 

Abstract classes are pretty helpful and provide an outline that we can modify as per our needs. To understand this, let’s see an example.

Let’s make an abstract class that will help us calculate the area of a circle and a triangle. We will use both abstract and non-abstract methods in our abstract class. 

import java.util.*;

//abstract class
abstract class Shapes         
{     //non-abstract method in an abstract class
double circle(int r)
{ 
    double area = (22*r*r)/7;
    return area;
}
      //abstract method
abstract double triangle(int b, int h);   
}

//abstract class is derived to override the abstract method
class RightTriangle extends Shapes       
{    
      //abstract method is overridden
double triangle(int b, int h)        
{
    double area = b*h/2;
    return area;
}
}

//abstract class is derived to override the abstract method
class EquilateralTriangle extends Shapes
{     //abstract method overridden again
double triangle(int b, int h)
{
    double area = 1.732*b*b/4;
    return area;
}
}

public class Main
{   
public static void main(String args[])
{ 
    Shapes a;
    Scanner sc = new Scanner(System.in);
 
    System.out.println("Enter the base and height of the triangle ");
    int base = sc.nextInt();
    int height = sc.nextInt();
    a = new RightTriangle();       //object is created to call method
    System.out.println("Area of right triangle is"+a.triangle(base,height));
   
      a = new RightTriangle();
    System.out.println("Enter the radius of the circle ");
    int radius = sc.nextInt();
    System.out.println("Area of circle is "+a.circle(radius));
    System.out.println("Enter the side of the equilateral triangle ");
    int side = sc.nextInt();
    a = new EquilateralTriangle(); 
    System.out.println("Area of equilateral triangle is"+a.triangle(side,side));
}
}

Output:

Enter the base and height of the triangle
1 2
Area of triangle is 1.0
Enter the radius of the circle
7
Area of circle is 154.0
Enter the side of the equilateral triangle
4
Area of the equilateral triangle is 6.928

In the code above, an abstract class “Shapes” is created. Both abstract and non-abstract methods are defined in it. 

After that, two classes, “RightTriangle” and “EquilateralTriangle”, are created, which inherit the abstract class. In these classes, the abstract methods are overridden to find the area of both a right triangle and an equilateral triangle using their respective formulas, thereby justifying the purpose of abstract methods. 

In the third class, “Main”, the main( ) method is defined, where an object is created to call the methods.

With that, the purpose of using an abstract class and methods should be clear.

Quick Recap

For a quick recap, let’s go over the following points and respective codes to better understand the key features of abstract classes and methods.

  1. A separate keyword abstract is used in Java to create a class abstract and methods.

For example,

abstract class Shapes
{
    abstract int area( );
}
  1. We cannot create an object for any abstract java class, i.e., instantiation is not feasible for abstract classes. We can, however, create references to an abstract class.
// An abstract class example
abstract class Test
{
public static void main(String args[])
{
// Try to create an object
Test t = new Test();
}
}

Output:

Main.java:6: error: Test is abstract; cannot be instantiated
Test t = new Test();
        ^
1 error
  1. In Java, an abstract class can exist in the absence of an abstract method. This enables us to create classes that can only be inherited and not instantiated.
import java.util.*;
// An abstract class example
abstract class Shape
{
    //non-abstract method
    double circle(int r)
    {
double area = 22*r*r/7;
return area;
    }
}
//inherited abstract class Shape
public class Circle extends Shape
{
   
}

public class Main
{
    public static void main(String args[])
    {
     Scanner sc = new Scanner(System.in);
    System.out.println("Enter the radius ");
    int radius = sc.nextInt();
    Circle obj = new Circle();
    double area = obj.circle(radius);
    System.out.println("Area = "+area);
    }
}

Output:

Enter the radius
7
Area = 154.0
  1. In Java, an abstract class can have constructors. When an instance of an inherited class is created, an abstract class constructor is called.
import java.util.*;
//An abstract class example
abstract class Shape
{
      //Abstract class constructor
Shape()
{
        System.out.println("Shape constructor is called");
}
    //abstract method
    abstract double circle(int r);
}

public class Circle extends Shape
{
      //Non-abstract class constructor
Circle()
{
        System.out.println("Circle constructor is called");
}
      //Abstract method is overridden
double circle(int r)
{
        double area = 22*r*r/7;
        return area;
}
}

public class Main
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the radius ");
        int radius = sc.nextInt();
      Circle obj = new Circle();
      double area = obj.circle(radius);
      System.out.println("Area = "+area);
    }
}

Output:

Enter the radius
7
Shape constructor is called
Circle constructor is called
Area = 154.0
  1. Final methods(methods that cannot be overridden) can be added to abstract classes.
import java.util.*;
//Abstract class example
abstract class Shape
{
      //final method which cannot be overridden
final double circle(int r)
{
        double area = 22*r*r/7;
        return area;
}
}
//Non-abstract class to inherit the abstract class
public class Circle extends Shape
{
   
}

public class Main
{
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the radius ");
    int radius = sc.nextInt();
    Circle obj = new Circle();
    double area = obj.circle(radius);
    System.out.println("Area = "+area);
}
}

Output:

Enter the radius
7
Area = 154.0
  1. We can define static methods in an abstract class that can be called without an object.
import java.util.*;
//An abstract class example
abstract class Shape
{
      //static method
static double circle(int r)
{
    double area = 22*r*r/7;
    return area;
}
}

public class Main extends Shape
{
public static void main(String args[])
{
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the radius ");
        int radius = sc.nextInt();
          //Static method is directly called without creating any object
        double area = Shape.circle(radius);
        System.out.println("Area = "+area);
}
}

Output:

Enter the radius
7
Area = 154.0

With this, we finally came to the end of our discussion of abstract classes and methods, let’s head on to see some frequently asked questions on the same.

Frequently Asked Questions

Can abstract classes have method implementation?

Yes, since an abstract class can contain both abstract and non-abstract methods.

What is the difference between abstract methods and concrete methods?

Abstract methods do not have a method body, while concrete methods do.

What is the difference between abstract class and interface?

The main difference is that abstract classes can contain abstract and concrete methods, while interfaces support only abstract methods. You can read more about the differences here.

Where do we use an abstract class?

An abstract class is used to define a base class, which the derived class can later override.

What is the abstract method?

A method that has no body and is declared as abstract is known as an abstract method.

Key Takeaways

In this article, we learned about abstract classes and methods. We learned how to use them and also why they are used. 

Abstract class and methods are an essential part of the OOPs concept, so questions about them are often asked in interviews. 

After reading this article, I hope you are now clear with the concepts and can easily tackle any question on it, but as always, practice makes perfect. So don’t forget to practice the other interview questions available on CodeStudio. Not only will the practice help you gain confidence for interviews, but it will also help you ace coding rounds.

Happy learning!