Abstract Class in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

"What is an abstract class in Java?" you might wonder. Well, an abstract class is a class that cannot be instantiated and is primarily meant to be subclassed by other classes.

A class that is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods. An abstract method is a method that is declared without any implementation. Abstract classes in Java implement the concept of Abstraction in Object Oriented Programming.

What Does Abstract Mean?

Abstract means a small description that gives you an imaginative idea about the concept. Like a summary, a small paragraph gives you a brief explanation of the whole book.

In the same way, Abstract Classes in Java simply declare the methods that are needed to be implemented by the class which extends the abstract class. The abstract class hides the internal details of method implementation showing only essential information to the user - the method name.

Introduction to Java Abstract Class

Hiding internal details and showing only the functionality is known as abstraction. Abstraction is one of the key concepts in Object Oriented Programming Paradigm.

In order to implement Abstraction, we use Abstract Classes or Interfaces. Abstract class in Java is a collection of abstract and non-abstract methods. Abstract methods do not have a body or implementation. The implementation of the abstract methods is provided by the child classes which extend the abstract class.

Basically, an Abstract Class is nothing but a blueprint for the child class. Abstract classes justify the layout of your idea and do not really implement them.

Syntax:

Real-life Example

Let's understand using a real-life example. Suppose you want to create a Calculator app.

  • Before actually writing code for that, you need to have a blueprint of the things you need for this project. Let's say you need functions like:

    • add() for addition
    • sub() for subtraction
    • mul() for multiplication
    • div() for division
  • All these methods will be treated as abstract methods because we are yet not thinking about their implementations. We are just collecting the basic functions we think we need in order to create a calculator app.

  • All these functions will be declared as Abstract methods inside the abstract class. These methods will not be implemented inside the abstract class. We will just be declaring them using the keyword "abstract".

  • The definition will happen inside the child class once the child class will extend to the abstract class.

I hope now you understand what exactly is an Abstract Class in Java. Now let's see some of the features of Abstract Class in Java.

Check, Complete Java Tutorial

Why Do We Need an Abstract Class in Java?

why do we need an abstract

Template Programming

Abstract classes provide a blueprint to be followed by the classes that extend the Abstract class. Abstract Class because it gives a predefined template for any future specific class that you might need.

  • Suppose you want to develop a calculator app for both Computers as well as Mobiles. The calculator app will perform similar functions on both devices, with some differences in their implementations.
  • We can have two classes - ComputerCalc and MobileCalc to represent the calculator interface in both devices.
  • Using abstract class, you can enforce a set of methods that must be implemented by both the classes - ComputerCalc and MobileCalc. Hence, the abstract class provides a blueprint to be followed by these child classes.

Loose Coupling

A method or class is almost independent in loose coupling, and they are less dependent on each other. In other words, the more one class or method knows about another class or method, the more tightly coupled the structure becomes. The more loosely connected the structure, the less the classes or methods know about each other.

To create a loosely coupled structure, abstract classes can be used. There are various benefits of Loose Coupling:

  • Easy maintenance of the code. Changes can be made to one class without affecting other classes.
  • Testing of loosely coupled structures is easier as we can divide the project into small modules and perform unit testing.

Code Reusability

Using an abstract class in an application saves time. We can declare an abstract method in the abstract class and call it from anywhere required. Abstract classes eliminate the need to repeatedly write the same code.

Abstraction

Data abstraction in Java helps the developers hide the actual method implementation from the end user and display only the method names (APIs). Abstract classes in Java help implement the concept of Abstraction as discussed before.

Dynamic Method Resolution

Last but not least is Dynamic Method Resolution. The Abstract Classes enable us with dynamic method resolution or the dynamic method dispatch process. The dynamic Method Resolution is a procedure where, at runtime, the calling of an overridden method is resolved.

This is how RunTime polymorphism is implemented. Whenever any method which is overridden is called by reference, it is JVM's responsibility to check the version of the method to execute depending upon the type of object.

Rules for Using Abstract Class in Java

Let's recap the rules to declare an abstract class -

  • You have to use the keyword abstract.
  • You cannot instantiate an abstract class.
  • An abstract class can contain both abstract and non-abstract methods.
  • You can include non-abstract final methods (a method that cannot be overridden) as well in your abstract class.
  • Final methods in abstract classes can not be abstract. They must be implemented in the abstract class itself.
  • You can also include constructors and non-abstract static methods in your abstract class.

Must Read- When do We Use an Abstract Class in Java?

Abstract Methods in Java

If you use the abstract keyword while declaring the method, it is called an Abstract Method.

An Abstract Method does not contain anybody. Whenever you declare an abstract method, you must end it with a semicolon as shown in the syntax below. An abstract method is always present inside an abstract class, you cannot declare it inside the regular (not abstract) class.

Let's see that calculator app example. You create an abstract class Calculator and you need basic 4 functions - addition, subtraction, multiplication, and division. So you just declare them as abstract methods inside the Calculator class. So whenever you extend the abstract class you need to define the abstract methods.

Let's understand some of the rules on the usage of the Abstract Method -

  • A method declared with the abstract keyword is called an Abstract method.
  • Abstract method can only be declared inside an abstract class or an interface.
  • Abstract methods must not contain any definition or body in abstract class.
  • You must end the declaration of the abstract method using ';'(semicolon).
  • To write the implementation code of these abstract methods, you must inherit the abstract class. Then the child class can write the definition for the abstract methods.
  • If you don't define the abstract method inside the child class, then you must declare the child class as abstract otherwise the compiler will throw an error. This is illustrated below:

Output:

Syntax of Abstract Method

The syntax for the abstract method is similar to any user-defined method in Java except you have to add abstract keyword at the start of the declaration. For example -

Let's see one example -

Abstract Class in Java Example

Let's understand in depth about Abstract class and methods using a java example.

See the following example -

Output:

Explanation:

  • We have created two classes - Add and Sub which extend the parent abstract class Calculator.
  • Since Add and Sub inherit the abstract class, they must provide the implementation of the abstract method display() otherwise, an error will be thrown.
  • Next, we declare a class 'Main', and in the main method, using the Calculator abstract class we declared two objects add and sub. Now using these objects, we can access the methods inside the child class and hence the output.

Interfaces and Abstract Classes

In order to achieve Abstraction in Object Oriented Programming in Java, there are 2 ways - Abstract Class and Interface. Now here comes the question, What is Interface?

Interfaces, like abstract classes, provide the blueprint of a class. It defines what your class will do, but not how it will do it. The interface acts as a way for us to achieve Full Abstraction in Java. The interface is just as same as any class. It can have variables and methods but by default, all the methods must be declared as abstract.

It means Interface can only contain abstract methods and not concrete (non-abstract) methods. I know this interface seems to be somewhat similar to an abstract class but what makes them different from one another are their features. Features like -

  • An Interface can have only abstract methods while abstract classes can have both abstract as well as concrete methods.
  • Interface supports multiple inheritance while Abstract Class does not support multiple inheritance.

An abstract class can implement an interface partially. It means:

  • It can provide the definitions of a few of its abstract methods and leave the rest as it is to be declared by the child classes that extend the abstract class.

Let's understand this with one example -

  1. First declare an interface. You have to use the keyword interface and forward to that interface name like this -

Here as you can see there are 3 non-defined methods (Abstract Methods).

  1. Now let's declare an abstract class that will implement the Scaler interface.

Here we have added the definition to 2 abstract method from the interface Scaler. So when you need to define an abstract method inside an abstract class, you must implement an interface.

  1. One method is remaining i.e ScalerForever(). Let's define it using our regular way by inheriting the abstract class. Declare a child class and extend the abstract class in it.
  1. Lastly, create object of the child class and run the program.
  1. Following will be the output -

Difference Between Abstract Class and Interface in Java

Abstract ClassInterface
An Abstract class doesn't provide full abstractionInterface does provide full abstraction.
Using Abstract classes, we cannot achieve multiple inheritanceUsing an Interface we can achieve multiple inheritance.
An abstract class can specify access modifiers for its members.We cannot use any access modifiers in interfaces because within an interface, by default, everything is public.
A class may inherit only one abstract class.A class may implement several interfaces (Multiple Inheritance).
An abstract class can have both abstract and non-abstract methods.An interface can have only abstract methods.

Also Read, Abstract Class Vs Interface: Detailed Comparison

Why Can’t We Create an Object of an Abstract Class?

If you have read till now, you know we cannot instantiate an abstract class. Meaning you cannot create an object of the Abstract class.

Abstract Class can have abstract methods and abstract method does not contain any body or definition inside it. This means that Abstract Class does not seem to be a complete class. It's just a template.

So imagine, if you create an object of that abstract class and try to access one of the abstract methods, it will throw an error because there is nothing inside the method to perform.

For an object to run any method, it must have somebody and the abstract method does not have any. Hence we cannot create the object of an abstract class.

The following error will be seen if one tries to create an object of an abstract class Student -

Accessing Constructors of Abstract Class

We can declare constructors of abstract classes. The Java Virtual Machine (JVM) is responsible to generate a default constructor for every class in Java Program if there is no User Defined Constructor present. This same applies to Abstract classes as well.

You can also create a user-defined parameterized constructor for your abstract class as well. Since abstract classes are meant to be inherited, the child classes can instantiate the parent class as per its need using the super() keyword.

Using the final keyword in an Abstract Class

The final keyword is used when you want to declare a variable, method, or class as non-modifiable once assigned. If your variable is final, you cannot change its value. If you declare a method as final, you cannot override it by inheritance, and if you declare a class as final, you cannot inherit it.

Notice that the whole concept of working of any abstract class depends on inheritance. You extend the abstract class and then you can provide implementations to the abstract methods declared within it.

But if you declare an abstract class final, you cannot inherit the class and hence you cannot provide any logic to the abstract method.

Now this contradicts every fact about abstract class. You can use "final" keyword separately and "abstract" keyword separately but not both simultaneously. Making an abstract entity final makes no sense as the entity is meant to be changed (or overridden).

Important Observations About Abstract Classes in Java

  • Use the 'abstract' keyword if you want to declare a class or method as abstract.
  • You have to provide implementation to all the abstract methods declared within the abstract class in its subclasses.
  • The class has to be abstract if you want to declare an abstract method within its scope.
  • You cannot create objects of an abstract class because the abstract class cannot be instantiated.
  • Whenever you create an object of the child class of an abstract class, the compiler calls the constructor of the abstract class automatically.
  • You can declare non-abstract final and static methods inside abstract classes.
  • Multiple inheritances cannot be achieved using an abstract class.

FAQs

Q. What is an abstract class in Java?

A. An abstract class in Java is a class that cannot be instantiated and is meant to be subclassed. It can contain both abstract and non-abstract (concrete) methods and can also have instance variables. Abstract classes are denoted by the "abstract" keyword in their class declaration.

Q. Why is an abstract class used in Java?

A. Abstract classes are used in Java to define common attributes and behaviors that can be inherited by multiple subclasses. They provide a blueprint for subclasses to follow and enforce the implementation of certain methods. Abstract classes can also define common fields and reduce code duplication.

Conclusion

  • Abstraction means has an imaginative concept but is yet to be implemented. Abstraction is one of the key principles in order to implement Object Oriented Programming Approach and design in Java.
  • Abstract classes have various advantages - Template Programming, Loose Coupling, Code Reusability, Abstraction, and Dynamic Method Resolution.
  • When you use the ‘abstract’ keyword while declaring a method, it is called an abstract method.
  • Abstract methods are implemented in the subclasses of the abstract class within which they are declared.
  • Abstract classes can implement one or more interfaces partially.
  • We can declare non-abstract static and final methods in Java. We must provide their implementation in the abstract class itself.
  • We cannot create instances of abstract classes because they may contain non-implemented methods which have no operations to perform.
  • Accessing constructors of abstract class is the same as that of any other class except you need to create an object of the child class which then calls the constructor of its parent abstract class.