blog

Home / DeveloperSection / Blogs / Abstraction in Java

Abstraction in Java

Anupam Mishra4276 11-Dec-2015

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

Another way, it shows only important things to the user and hides the internal details for example sending WhatsApp message, you just type the text and ping the message. You don't know the internal processing about the message delivery.

The main advantage of Abstraction that lets you focus on what the object does instead of how it does it.

There are only two ways to achieve abstraction in java
1. Abstract class (partially):

If you are declared with abstract keyword of a class is called abstract class. It can have abstract and non-abstract method (method with body).

It need to be extended and its method implemented to another class.it can’t be instantiated.

abstract class Abc{}

2. Interface (Fully):

Interface are used to achieving fully Abstraction in java. If you want to achieve multi-threading in java then interface is an only way for that. By default, interface fields are public, static and final and methods are public and abstract. You can only defined abstract method in interface not giving the body of method. You are not create instance of interface same as abstract class.

If you want to implements more than one interface that are possible by using extends keyword in java. if you are not adding keyword public abstract before methods and public static final before fields then i.e. also compiled successfully. after compilation compiler will be adding itself.


The syntax of the Interface is as follow:

interface MyInterface {
public abstract void displayName ();
}
For Example,
interface MyInterface
{  
       void DisplayName();  
}  
interface MyInterface2 extends MyInterface // extend another interface
{
       void DisplayAdd();  
}  
class TestingInterface implements MyInterface2
public void DisplayName()
{
       System.out.println("Anupam Mishra");
}  
public void DisplayAdd()
{  
           System.out.println("Allahabad");
}  
public static void main(String args[])
{  
       TestingInterface obj =
 new TestingInterface();  //instantiate object of the class
       obj.DisplayName();  
       obj.DisplayAdd();  
 }  
 }  
Output:

Anupam Mishra

Allahabad


Updated 13-Mar-2018

Leave Comment

Comments

Liked By