Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Abstraction in Java?
3.
Abstract Class in Java
3.1.
Example of Abstract Class
4.
Abstract Method in Java
4.1.
Example of Abstract Method
5.
Implementation of Abstract Class and Methods
5.1.
Syntax
5.2.
Syntax
6.
Real Scenario of Abstract Class
7.
Real Scenario of Abstract Method
8.
Constructors of Abstract Class
9.
Need an Abstract Class in Java
10.
Frequently Asked Questions
10.1.
What is the abstract class in Java?
10.2.
What is abstraction in Java?
10.3.
Why is abstract class used in Java?
10.4.
What are the 4 types of abstraction?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Abstract Class in Java

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

A Class declared by the abstract keyword is known as Abstract Class. It may or may not have abstract and non-abstract methods, allowing us to define common attributes and methods that subclasses can extend. It’s a restricted class that cannot be used to create objects.

Abstract Class in Java

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

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

Also see, Duck Number in Java 

What is Abstraction in Java?

Abstraction is a concept that focuses on hiding unnecessary details and showing essential information to the user. To achieve Abstraction in Java, we use Abstract Classes and Interfaces. It promotes the concept of encapsulation, as the internal working of the objects is hidden, and provides a simplified interface to interact with the objects. We can concentrate on the essential features of the object by abstracting away the unnecessary details, making our code reusable and manageable.

We can implement abstraction in two ways:

  1. Abstract class (0 to 100%)
  2. Interface (100%)

Also see, Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Abstract Class in Java

A Class that may contain abstract and non-abstract methods and is declared using the “abstract” keyword is known as Abstract Class. It provides common functionality and attributes that subclasses can extend and override.

Some crucial points to keep in mind about Abstract Classes are:

  • To define an abstract class, you use the abstract keyword in the class declaration. 
     
  • 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.
     
  • They can contain abstract methods, which are declared without a method body and end with a semicolon. 
     
  • Abstract classes can also have concrete methods (methods with a body) that provide default behavior and can be used by subclasses.
     
  • They can provide a partial implementation of an interface or a common functionality shared by multiple subclasses.

Example of Abstract Class

/* abstract class */
abstract class WarGame {
   protected String character_name;
   protected int attack_points;

   public abstract void attack();

   public abstract void save_health();
}

class Dragon extends WarGame {

   public void attack() {
       /* specific implementation for dragon attack */
   }

   public void save_health() {
       /* specific implementation for dragon defence */
   }
}


Here, we have created an Abstract Class ‘WarGame’ that defines common attributes and methods like ‘attack’ and ‘save_health’. The subclass ‘Dragon’ extends the ‘WarGame’ class and provides its specific implementation of the Abstract Methods. This allows us to create different characters in the game and customizing their common behaviors,

To know more about Hashcode Method in Java click here

Abstract Method in Java

It is a method without implementation or body and is declared in an Abstract Class. If a subclass extends an Abstract Class, it must implement all the Abstract Methods of the Abstract Class. It promotes the concept of polymorphism, abstraction, and code reusability by defining common methods that the different classes can implement.

Example of Abstract Method

abstract class Job {
  
   /* abstract methods */
   public abstract int base_salary();

   public abstract int CTC();
}

class DataScientist extends Job {

   public int base_salary() {
       /* base salary for data scientists  */
   }

   public int CTC() {
       /* CTC for data scientists */
   }
}


Here, we have an Abstract Class ‘Job’ having two Abstract methods, ‘base_salary’ and ‘CTC’. The subclass ‘DataScientist’ extends the class ‘Job’ and has its own implementation for the abstract methods defined in the abstract class. 

Implementation of 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:

Syntax

abstract class Class_name
{
    .....
}


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

Syntax

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. 

Real Scenario of Abstract Class

A real-life scenario where abstract classes are commonly used is in designing and implementing various vehicles. Let's consider a simple scenario where we have different types of vehicles, such as bikes, cars, etc. To represent these vehicles, we can create an abstract class called vehicle:

/* abstract class */
abstract class vehicle {
   protected String company;
   protected int price;


   /* constructor for the abstract class*/
   public vehicle(String company, int price) {
       this.company = company;
       this.price = price;
   }


   /* abstract methods */
   public abstract void ApplyBrakes();
   public abstract void Accelerate();


}

class Bike extends vehicle{
  
   /* constructor for the Bike class */
   public Bike(String company, int price) {
       super(company, price);
   }

   public void ApplyBrakes() {
       /* implementation to apply brakes of a bike*/
   }

   public void Accelerate() {
       /* implementation to accelerate a bike */
   }

}


The code above is for a vehicle simulation system. We have an Abstract Class ‘vehicle’ having common methods and properties that all vehicles should have. The methods ‘ApplyBrakes’ and ‘Accelerate’ are of an abstract type, as their implementation varies from vehicle to vehicle. A subclass ‘Bike’ provides its own implementation to the Abstract Methods of the Abstract Class. There can be many more such subclasses for different vehicles with their own implementations for the Abstract Methods of the Abstract Class.

Real Scenario of Abstract Method

A real-life scenario where abstract methods are commonly used is in resizing the image. Let's consider a simple scenario where we have methods to resize the image, such as height and width. We also have types of images such as jpeg and png. To represent these resizing methods, we can create an abstract class called ImageResizer:

abstract class ImageResizer {
   /* abstract methods*/
   public abstract void changeHeight(int height);
   public abstract void changeWidth(int width);
}

class jpegImageResizer extends ImageResizer {
   public void changeHeight(int height) {
       /* implementation for changing the height of a jpeg image */
   }
   public void changeWidth(int width) {
       /* implementation for changing the width of a jpeg image */
   }
}

class pngImageResizer extends ImageResizer {
   public void changeHeight(int height) {
       /* implementation for changing the height of a png image */
   }
   public void changeWidth(int width) {
       /* implementation for changing the width of a png image */
   }
}


The above code is for the image resizer. We have an Abstract Class, ‘ImageResizer,’  having two Abstract Methods for changing the height and width of an image. The subclass ‘jpegImageResizer’ is for adjusting the height and width of a jpeg image, whereas the subclass ‘pngImageResize’ is for adjusting the height and width of a png image. Both of these classes use the abstract methods ‘changeHeight’ and ‘changeWidth’ and have their own implementation for these methods.

Constructors of Abstract Class

An Abstract Class can have any Constructor that any other class may have. It cannot be instantiated on its own, but it is invoked when an object calls the Constructor of its subclass.

Let’s see some implementation details of the Constructors of an Abstract Class.

Code

/* abstract class */
abstract class parent {
   String value1;
   String value2;

   /* constructor with no parameter */
   public parent() {
       this.value1 = null;
       this.value2 = null;
   }

   /* constructor with one parameter */
   public parent(String value1) {
       this.value1 = value1;
       this.value2 = null;
   }

   /* constructor with two parameters */
   public parent(String value1, String value2) {
       this.value1 = value1;
       this.value2 = value2;
   }
}

class child extends parent {
  
   public child() {
       super();
   }

   public child(String value1) {
       super(value1);
   }

   public child(String value1, String value2) {
       super(value1, value2);
   }
}


class Solution {

   public static void print(child object) {
       System.out.println(object.value1 + " " + object.value2);
   }

   public static void main(String[] args) {
       /* invoking all three constructors */
      child object1 = new child();
      child object2 = new child("first_string");
      child object3 = new child("first_string", "second_string");
      print(object1);
      print(object2);
      print(object3);
   }
}


Output

null null
first_string null
first_string second_string


In this example, an Abstract Class ‘parent’ has three types of constructor, one with no parameter and the other two with one and two parameters. These Constructors are invoked by the subclass ‘child’ using the ‘super()’ keyword. We can’t create the objects of the class ‘parent’, as it is an Abstract Class. So we have created the objects of the class ‘child’, which inherits the constructor from the Abstract Class. 

Need an Abstract Class in Java

  • The Abstract Classes encapsulate the related properties and behaviors, promoting data and information hiding.
     
  • These are used in various libraries to provide a base class with common functionalities. Subclasses can extend these base classes to customize the methods according to their needs.
     
  • By encapsulating the common methods in an Abstract Class, we can reduce the repetition of methods, minimizing the code length.
     
  • It can have both abstract and concrete methods. So the concrete method can implement the default behavior, and the abstract method defines the behavior depending on the subclass implementing it. This makes our code flexible.
     
  • We can write the same code for the subclasses of an Abstract Class as they share common properties and methods, which makes the code reusable. 
     

Know What is Object in OOPs here in detail.

Frequently Asked Questions

What is the abstract class in Java?

An Abstract Class is a Class that cannot be instantiated directly and acts as the blueprint for its subclasses. It may contain abstract methods (without implementation) and non-abstract methods (with implementation) to provide common functionalities to its subclasses.

What is abstraction in Java?

Abstraction in Java allows us to represent the essential characteristics of an object without exposing the details of its internal implementation. It helps in creating more understandable and maintainable code by focusing on what an object does rather than how it does it.

Why is abstract class used in Java?

An abstract class is used in Java to provide a common blueprint for related classes. It allows partial implementation, with some methods having concrete code and others being left abstract. It defines method contracts that subclasses must implement, ensuring consistent behavior across related objects.

What are the 4 types of abstraction?

There are 4 types of abstraction that are data abstraction, procedural abstraction, control abstraction, and hierarchical abstraction. In data abstraction, data objects are presented in a way that only relevant information is visible. Procedural abstraction helps to hide the implementation of procedures or functions. Control abstraction helps to hide the intricate control flow details, such as loops and conditionals. Hierarchical abstraction helps to organize complex systems into layers, each providing a higher-level view of the system.

Conclusion

In this article, we learned about an abstract class in Java. 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. 

Recommended Readings:


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 Coding Ninjas Studio. Not only will the practice help you gain confidence for interviews, but it will also help you ace coding rounds.
Happy learning!

Previous article
Anonymous Class In Java
Next article
BigInteger in Java
Live masterclass