by BehindJava

What is abstraction in Java

Home » java » What is abstraction in Java

In this tutorial we are going to learn about abstraction in java.

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don’t know the internal processing about the message delivery.

Ways of achieving abstraction in Java

Abstract class in Java:

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Why abstract class cannot be instantiated?

We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.

Let’s say the requirements are partially given to a developer, in this case we can go for abstract class which mean to say that this an incomplete class for which an object cannot be created but can extend the abstract class.

What are the advantages of abstract class over interfaces?

Abstract classes are a re-use mechanism for the class hierarchy for behavior and structure which isn’t complete on its own.

Abstract classes can contain abstract and non-abstract methods where interfaces can contain only abstract methods.

Interfaces are mechanism for specification of requirements on a module (e.g. class) independently of the concrete implementation. All other differences are technical details, important is different usage.

Sample Code Snippet:

abstract class Bank{    
abstract int getCarLoan();    
}    
class SBI extends Bank{    
int getCarLoan(){return 700000;}    
}    
class PNB extends Bank{    
int getCarLoan(){return 800000;}    
}    
    
class TestBank{    
public static void main(String args[]){    
Bank b;  
b=new SBI();  
System.out.println("Rate of Interest is: "+b.getCarLoan()+" %");    
b=new PNB();  
System.out.println("Rate of Interest is: "+b.getCarLoan()+" %");    
}}    

Interface in Java:

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Java Interface also represents the IS-A relationship and cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.

Please refer to this https://www.behindjava.com/java-two-interfaces/ for interface example.