This tutorial explains what is Abstraction in Java along with programming examples. You will also learn what is an abstract class & why is it used:
In this JAVA Series, we will discuss the important features of object-oriented programming (OOP) that are also known as four pillars i.e. Abstraction, Encapsulation, Inheritance, and Polymorphism.
The first pillar of OOP is “Abstraction”. “Abstraction is the process of selecting data to show only the relevant information to the user.”
=> Take A Look At The Java Beginners Guide Here.
Table of Contents:
Abstraction In OOP
In simple terms, abstraction “displays” only the relevant attributes of objects and “hides” the unnecessary details.
For example, when we are driving a car, we are only concerned about driving the car like start/stop the car, accelerate/ break, etc. We are not concerned about how the actual start/stop mechanism or accelerate/brake process works internally. We are just not interested in those details.
What we are concerned about is the “abstract” view of these operations that will help us to propel the car forward and reach our destination. This is a simple example of abstraction.
Thus the car has all the mechanisms and processes in place but from the end user’s perspective, i.e. car driver’s perspective he/she will be interested only in the abstract view of these processes.
Abstraction reduces the programming efforts and thereby the complexity. An end-user using the application need not be concerned about how a particular feature is implemented. He/she can just use the features as required.
Thus in abstraction, we deal with ideas and not the events. This means that we hide the implementation details from the user and expose only the functionality to the end-user. Thereby the user will only know “what it does” rather than “how it does”.
Abstraction in OOP can be of two types.
#1) Data Abstraction
In data abstraction, we mostly create complex data types and hide their implementation. We only expose the operations to manipulate these data types without going into the details of their implementation.
One advantage of this approach is that we can change the implementation anytime without changing the behavior that is exposed to the user.
#2) Control Abstraction
Control abstraction collects all the control statements that are a part of the application and exposes them as a unit. This feature is used when we have to perform a working feature using this control unit.
Control abstraction forms the main unit of structured programming and using control abstraction we can define simple functions in complex frameworks.
What Is Abstraction In Java
As Java is an OOP language, abstraction can be seen as one of the important features and building blocks of the Java language. In Java, abstraction is implemented using an abstract class and interface.
So how do we implement abstraction in Java? Java provides a non-access modifier “abstract” for implementing abstraction. This abstract modifier can be used with classes and methods but not variables.
The interface provides complete abstraction i.e. it only provides method prototypes and not their implementation. An abstract class provides partial abstraction wherein at least one method should not be implemented.
In this tutorial, we will discuss abstraction with abstract classes in detail. We will explore interfaces in detail in our subsequent tutorials.
Java Abstraction Example
Let’s consider the below example.
//abstract class abstract class Car{ abstract void accelerate(); } //concrete class class Suzuki extends Car{ void accelerate(){ System.out.println("Suzuki::accelerate"); } } class Main{ public static void main(String args[]){ Car obj = new Suzuki(); //Car object =>contents of Suzuki obj.accelerate(); //call the method } }
Output:
The simple abstraction example that is given above has a class Car. In this class Car, we have an abstract method to accelerate (). Then we inherit this class in the Suzuki class. Inside the Suzuki class, we implement the accelerated method.
The above example simply shows the way in which an abstract class is defined, inherited, and then used in the program.
What Is Java Abstract Class
We already mentioned that Java implements abstraction using abstract classes and interfaces. Let’s first explore all about the abstract class.
An abstract class can be defined as a class declared with the keyword “abstract” and has a restriction that it cannot be instantiated.
An abstract class may or may not have any abstract method (a method with no implementation). As far as JVM is concerned, an abstract class is an incomplete class that does not have a complete behavior.
The general syntax of an abstract class is given below:
abstract class <classname> { public abstract void abstractMethod(); public void normalMethod() { //method body } }
As shown in the syntax of the above abstract class, we can have abstract as well as non-abstract methods in an abstract class. The keyword ‘abstract’ precedes the class declaration.
In a nutshell, an abstract class can be described as shown below.
Abstract Method In Java
An abstract method is a method preceded by an ‘abstract’ keyword without any implementation. An abstract method is declared inside an abstract class.
An abstract method is the one that makes a class incomplete as it doesn’t have an implementation. Hence when we include an abstract method in the class, naturally the class becomes incomplete.
We can use the abstract method by implementing it in a subclass i.e. a class inherits the abstract class and then implements or provides the code for all the abstract methods declared in the abstract class by overriding them.
Thus it becomes compulsory to override the abstract method in the subclass. If the abstract method is not implemented in the subclass as well, then we have to declare the subclass also as “abstract”.
The general declaration of the abstract method is:
abstract void methodName (parameter_list);
While writing the abstract method, we need to remember the following rules:
- A class containing one or more abstract methods is an abstract class.
- Certain other keywords should not be used with the abstract keyword.
Thus, the following combinations are illegal in Java.
- final
- abstract native
- abstract static
- abstract private
- abstract synchronized
- abstract strictfp
Let’s implement an example of an abstract class and an abstract method.
//abstract class abstract class Bank{ abstract int getInterestRate(); } //concrete class class Citi extends Bank{ int getInterestRate(){return 7;} } //concrete class class HSBC extends Bank{ int getInterestRate(){return 6;} } class Main{ public static void main(String args[]){ Bank b; b = new Citi (); // concrete class object System.out.println("Citi Rate of Interest is: "+b.getInterestRate()+"%"); b = new HSBC (); // concrete class object System.out.println("HSBC Rate of Interest is: "+b.getInterestRate()+"%"); } }
Output:
In the above example, we have a Bank class. In this class, we have an abstract method, getInterestRate (). Then we declare two classes – ICICI and BOI that inherit from the Bank class. Both these classes implement the getInterestRate () method by returning their respective interest rates.
Then in the main method, we create a bank object. First, the bank object contains an object of ICICI class and displays the interest rate. Next, the BOI object is created and it displays the interest rate.
Thus, we can assume that the Bank class is a sort of a sketch or a structure that allows us to get an interest rate. From this structure, we can create as many concrete classes as we want, and then we can get the respective interest rates for each bank object (this is shown in the main method).
What Is The Use Of An Abstract Class In Java
Why do we use an abstract class when in reality it does not have any implementation of its own?
Along with the answer to the above question, we will also illustrate how to use an abstract class in the example that follows.
Let’s consider an example of Vehicles. We know that Vehicles can be of many types. We can have Cars, Scooters, bikes, mopeds, buses, etc. Though there are many types of vehicles, they have some properties or attributes that are common to all vehicles irrespective of their types.
For example, each vehicle has a model, chassis number, color, etc. Each of them has functions like start, stop, accelerate, brake, etc. Now each vehicle will have the above properties and methods that are common to the others as well. At the same time as to vehicle users, we might not be interested in some aspects.
For example, if a person is driving a car, what he/she will be interested in is just to start and stop the vehicle or accelerate or brake the vehicle. He/she will not be interested in knowing how the vehicle starts or stop. We are only interested in the abstract working of the functions and not in their details.
Now if we want to represent the above example system into a software application, then how do we design it? First of all, we will implement some abstractions. Now, we know that some functions are common but depending on each model the implementation of these functions will be different.
To begin with, we declare an abstract class “Vehicle”.
We have shown this system below:
So we will have an abstract class Vehicle and there will be a concrete class representing each model of the vehicle. For illustration purposes, we have used only three models i.e. car, bike, and scooter.
Given below is the class hierarchy from the above system.
abstract class Vehicle{ abstract void start () ; abstract void stop (); abstract void accelerate (); abstract void brake (); } class Car extends Vehicle{ void start () { //code here…} void stop () { //code here…} void accelerate () { //code here…} void brake () { //code here…} } class Bike extends Vehicle{ void start () { //code here…} void stop () { //code here…} void accelerate () { //code here…} void brake () { //code here…} } class Scooter extends Vehicle{ void start () { //code here…} void stop () { //code here…} void accelerate () { //code here…} void brake () { //code here…} }
So we will have a Vehicle abstract class and three classes Car, Bike, and Scooter. Each of these classes will extend the Vehicle class and override each of the abstract methods.
Thus in general, whenever we have to represent such a system that has common methods or operations to represent, then to present only the outer perspective to the user, we go for abstraction. As a result, we take out the common methods and represent them as abstract methods and collect these abstract methods in a common abstract class.
Once we have the outline of a system represented as an abstract class and the operations as abstract methods, we can then derive any number of classes from the given abstract class and override the abstract methods to implement these operations for each class.
This way it becomes useful to design a system.
Abstract Class And Interface
We have seen the abstract class above. Interfaces are yet other building blocks that implement abstraction. Interfaces are contracts, and classes implementing the interface have to honor these contracts.
Contracts in interfaces are nothing but methods that are not implemented. Inside interfaces, we will only have method prototypes. There will not be a single implementation of methods inside interfaces.
If we have an interface declaration as follows:
public interface interfaceA{ void myInterfaceMethod (); }
Then any class that implements the interfaceA needs to override the ‘myInterfaceMethod’.
If at all we don’t override the method in a class, then that class is represented as abstract.
abstract class TestClass implements interfaceA{ // not a compulsion to override myInterfaceMethod. }
We will have a separate tutorial on the interface later.
Next, let us discuss some of the differences between Abstract classes and Interfaces in Java.
Difference Between Abstract Class And Interface
Abstract class | Interface |
---|---|
An abstract class can have abstract and/or non-abstract methods. | An interface can only have abstract methods. |
The abstract may or may not contain the final variables. | Interfaces can final variables as default variables. |
An abstract class can have final, static or non-static or non-final variables. | Interfaces can have only final and static variables. |
An abstract class may provide interface implementation. | Interfaces cannot implement an abstract class. |
An abstract class is inherited using the “extends” keyword. | The interface is implemented using the “implements” keyword. |
An abstract class can extend other classes or implement multiple interfaces. | The interface can only implement another interface. |
An abstract class can have private or protected data members apart from public members. | Interface members are by default public. |
When To Use Abstract Class And Interface In Java
The decision about when to use abstract class and when to use interfaces in Java applications should be taken intelligently after thoroughly understanding the problem at hand. There are two aspects that we have to consider as shown below.
Abstract Classes With Partial Behavior
We know that abstract classes may not be completely implemented. They can have partial behavior. On the other hand, interfaces do not have any implementation. So when we have to choose between an abstract class and an implementation, then we need to consider this aspect of our application.
This means that we have to first decide whether the application that we are designing is having any common partial implementation that we can separate in an abstract class.
For example, consider that we are designing a web application. For this, we will have to use some web technology like Servlet, REST API, etc. Now each of these web technologies has some techniques or steps that are to be implemented irrespective of the application that we are developing. Then we build our customized application.
So in this case, the definite code that the web technology has to execute can be put in an abstract class. Can we have an interface for this? No. This is because the interface cannot have an implementation.
Contract Only Interfaces
We know that interfaces have contracts or methods that are a part of them. These methods are only prototypes. We have to implement these interfaces in a class and then override the methods.
Now consider the Map interface of Java Collections Framework. Many classes like HashMap, TreeMap, HashTable, etc. implement this interface. Each of these classes has a different implementation. They do not have any common behavior that can be represented in the abstract class.
So what we do is we design an interface with method prototypes and then implement each of the classes.
This way we should weigh each factor properly before we choose between an abstract class and interface.
Difference Between Abstraction And Encapsulation
Let’s discuss some of the differences between abstraction and one more important feature of OOP i.e. encapsulation.
Abstraction | Encapsulation |
---|---|
Process of gaining and abstracting the information | Process of binding the information. |
The abstraction technique is at the design or interface level. | The encapsulation mechanism is at the implementation level. |
Abstraction hides the details. | Encapsulation binds the information in one unit this ensuring information security. |
Abstraction is implemented using abstract classes and interfaces. | Access modifiers namely public, private, and protected and default play a role in encapsulation. |
In abstraction, the only abstract view is presented to the user while complex and detailed data is hidden from the user. | In encapsulation, data is bundled as a unit and can be protected or made accessible using access modifiers and getter and setter methods. |
Frequently Asked Questions
Q #1) Is Abstraction and Data hiding the same?
Answer: No, Abstraction and Data hiding is not the same. But both are important features of object-oriented programming. While abstraction is a process of hiding the background details, data hiding is a technique of insulating the data from direct access.
Q #2) What are the Advantages of Abstraction?
Answer: Few advantages of Abstraction are given below:
- By hiding the background details and exposing only the abstract view to the user, abstraction makes code simpler and more readable.
- As abstraction shields unnecessary details, it makes code smaller.
- Code maintenance can become complex and difficult without abstraction.
Q #3) Why is Abstraction so important?
Answer: Abstraction allows us to hide background details that are important and can lead to chaos if leaked to the world. By hiding the background details and exposing only the required interface to the user, abstraction makes applications simpler.
Q #4) Explain Abstraction with a real-time example.
Answer: There are many real-time examples of abstraction including geometric shapes, vehicles, etc. Yet another example is the ATM (Automated Teller Machine). The ATM supports operations like cash withdrawal, balance checking, money transfer, etc. But we are not aware of how these operations work internally.
We are only given a monitor with a user interface to select and perform the required operations.
Q #5) Can we achieve Abstraction without Encapsulation?
Answer: Abstraction shields the implementation details and encapsulation hides the object details. The object is the abstract form of the real world and its details are hidden using encapsulation. Thus encapsulation is required for abstraction.
Conclusion
In this tutorial, we have discussed abstraction in Java in detail. Abstraction is a technique of hiding unnecessary details from the user. The user is only given access to the details that are relevant. Vehicle operations or ATM operations are classic examples of abstractions in the real world.
When we use ATMs, we are only interested in performing the operations like cash withdrawal, etc without having to know the details about how exactly that operation is performed internally.
Java provides abstraction through abstract classes and interfaces. While interfaces provide 100 % abstraction, abstract classes provide partial abstraction. The choice between interfaces and abstract classes should be made depending on the application to be developed and also what information is to be exposed to the user.
We also discussed the abstract methods in this tutorial along with the differences between abstract classes and interfaces.
=> Check ALL Java Tutorials Here.