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

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

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

What Does Abstract Mean?

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

In the same way, Abstract Classes in Java simply declares the methods that need 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

*Abstraction is the practice of Hiding internal details and showing only the functionality. It is one of the key concepts in the 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 child classes provide the implementation of the abstract methods, 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 you now understand what an Abstract Class is in Java. Let's examine some of its features.

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 Computers and mobile devices. The 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 for these child classes.

Loose Coupling

In loose coupling, a method or class is almost independent and 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.

Abstract classes can be used to create a loosely coupled structure. 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 write the same code repeatedly.

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 an overridden method is called by reference, the JVM is responsible for checking 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 the calculator app example. You create an abstract class, Calculator, and you need the basic four functions—addition, subtraction, multiplication, and division. You declare these as abstract methods inside the Calculator class. 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 define 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 the abstract keyword at the start of the declaration. For example -

Let's see one example -

Abstract Class in Java Example

Let's understand abstract class and methods in depth 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

There are two ways to achieve Abstraction in Object-Oriented Programming in Java: Abstract Class and Interface. Now, here comes the question: What is an Interface?

Interfaces, like abstract classes, provide a class's blueprint. They define 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 simple as any class. It can have variables and methods, but all the methods must be declared abstract by default.

This means that the 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 their features make them different from one another. Features like -

  • An interface can only have abstract methods, while abstract classes can have both abstract and 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 methods from the interface Scaler. So, when defining an abstract method inside an abstract class, you must implement an interface.

  1. One method remains, ScalerForever(). Let's define it using our regular method 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. This means you cannot create an object in the Abstract class.

Abstract Class can have abstract methods; the abstract method does not contain any body or definition. 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. If no user-defined constructor is present, the Java Virtual Machine (JVM) generates a default constructor for every class in the Java Program. This same applies to Abstract classes.

You can also create a user-defined parameterized constructor for your abstract class. Since abstract classes are meant to be inherited, the child classes can instantiate the parent class as needed 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 any abstract class's whole concept of working 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 implement 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 multiple subclasses can inherit. 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 implementing An object-oriented programming approach and designing 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 partially implement one or more interfaces.
  • 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 with no operations to perform.
  • Accessing constructors of an abstract class is the same as accessing constructors of any other class, except you need to create an object of the child class, which is then called the constructor of its parent abstract class.