In object-oriented programming, Abstract Class in Java plays a crucial role in defining the blueprint for a group of related classes. It serves as a foundation for creating reusable and maintainable code by encapsulating common behaviors and properties. Unlike regular classes, an abstract class can include both abstract methods—methods without a body—and concrete methods with implementations. This unique combination allows developers to enforce a consistent structure while retaining flexibility for subclasses to provide specific implementations. In this blog, we will discuss the concept of abstract classes.
A similar concept is used in object-oriented programming, called abstraction, where we only use a class without worrying about how it’s working.
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.
What is 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.
Syntax of Abstract Class in Java
Here’s the basic syntax for defining an Abstract Class in Java:
abstract class ClassName {
// Abstract method (does not have a body)
abstract void methodName();
// Concrete method (has a body)
void anotherMethod() {
// Method implementation
}
// Fields (optional)
int field;
}
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,
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.
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.
Syntax of Abstract Method in Java
abstract returnType methodName(parameters);
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.
Real Scenario of Abstract Class in Java
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 Java 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
Java
Java
/* 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); } }
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.
Properties of Abstract Class
Abstract Methods: Contains at least one pure virtual function, making it mandatory for derived classes to implement.
Cannot be Instantiated: Cannot create objects of an abstract class directly.
Inheritance: Provides a common interface for derived classes to follow.
Partial Implementation: Can include both implemented and pure virtual methods.
Destructors: Can have virtual destructors for proper cleanup of derived class resources.
Difference Between Abstract Class and Interface in Java
Parameters
Abstract Class
Interface
Definition
A class that can have abstract and concrete methods.
A blueprint for a class that can have abstract methods (and default, static methods since Java 8).
Inheritance Type
Supports single inheritance.
Supports multiple inheritance.
Keyword Used
Declared using the abstract keyword.
Declared using the interface keyword.
Methods
Can have both abstract methods and methods with implementation.
All methods are abstract by default (until Java 8, which introduced default and static methods).
Fields
Can have instance variables (fields).
Can only have constants (static final fields).
Access Modifiers for Methods
Methods can be public, protected, or private.
All methods are public by default.
Constructor
Can have constructors.
Cannot have constructors.
Multiple Inheritance
Not supported (directly).
Supported.
When to Use
Use when classes share some behavior but are not completely related.
Use to define a contract that implementing classes must follow.
Frequently Asked Questions
How to declare a class abstract in Java?
To declare a class abstract in Java, use the abstract keyword before the class declaration. For example:
abstract class ClassName { // Class content }
This prevents direct instantiation of the class.
What is the difference between abstraction and abstract class?
Abstraction is a concept of hiding implementation details and showing only functionality, achieved using abstract classes and interfaces. An abstract class is a specific Java construct to implement partial abstraction with both abstract and concrete methods.
Is it possible to create an instance of an abstract class?
No, you cannot create an instance of an abstract class. However, you can create instances of its subclasses that provide implementations for all abstract methods. Abstract classes serve as templates for other classes.
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.
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.