Hurry! 20% Off Ends SoonRegister Now

Abstraction in Java

This blog details what is Abstraction in Java with programming examples. You'll also learn what an abstract class is and why it's useful.

 

Abstraction is the basic concept of Object-Oriented Programming which revolves around real-life entities.

Are you interested in taking up Core Java Certification Training? Enroll Now for Core Java Training!

Abstract classes

Abstract classes are used to hide implementation details from the user. They are declared using the abstract keyword. Abstract classes cannot be instantiated. Abstract methods are only method signatures. They don’t contain any method body. An abstract class can have abstract and concrete methods. But if anyone method in a class is abstract, then we need to declare class also as abstract.

A class extending abstract class must override all the abstract methods. It will have an implementation code of abstract methods. Let us go through the below example for understanding it.

abstract class class2{

   public void print(){
     System.out.println("Concrete Method - Class2");
   }

   abstract public void print2();
}

public class class1 extends class2{

   public void print2()
   {
       System.out.println("Abstract Method - Class1");
   }

   public static void main(String args[]){
       class1 obj = new class1();
       obj.print2();
       obj.print();
   }
}

Output:

Abstract Method - Class1
Concrete Method - Class2

Here, we can see class2 is a simple class extending abstract class class1. So class2 must define abstract method print2 in class2 declaration. Through a class2 object, we can access abstract and concrete both methods of an abstract class.

Interfaces

Interfaces in Java are known as a blueprint of a class. It is the same as class, but the only difference between them is interfaces have only static constants and abstract methods. These methods are declared without a body in interfaces. Interfaces don’t assume how methods will be implemented. The class that implements the interface has the capability to implement that method.

Any number of classes can implement any number of interfaces. To implement an interface, a class must provide an implementation code of all the methods declared in the interface. Each class can have its own version of the body. Java supports multiple inheritances by using the interface concept.

The general form of interface is:

access interface name {
return-type method-name1(parameter-list);
type final-varname1 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

 MindMajix YouTube Channel

Why interface is required?

Now, let us understand the importance and usage of an interface in a better and simpler way.
There are so many shapes exist and they have their different unique qualities. Area of rectangle and circle is different. They are also drawn differently. So suppose, we have one interface called shape which has 2 methods – draw() and area(). Now, whichever class implements this interface can have its own version of method implementation.

package mypack;
 
interface shape {
 
    //implicitly public, static and final
    public String title="Shape";
    
    //interface methods are implicitly abstract and public
    void draw();
    
    double getArea();
}
 
class circle implements shape {
 
    private double r;
 
    public circle(double r){
        this.r = r;
    }
    
 
    public void draw() {
        System.out.println("Circle Drawing");
    }
    
    
    public double getArea(){
        return 3.14*this.r*this.r;
    }
 
}
 
class rectangle implements shape {
 
    private double width;
    private double height;
    
    public rectangle(double w, double h){
        this.width=w;
        this.height=h;
    }
 
    public void draw() {
        System.out.println("Rectangle Drawing");
    }
 
    public double getArea() {
        return this.height*this.width;
    }
 
}
 
public class HelloWorld
{
    public static void main(String[] args) {
        
        //programming for interfaces not implementation
        shape s1 = new circle(5);
        
        s1.draw();
        System.out.println("Circle Area="+s1.getArea());
        
        //switching from one implementation to another easily
        s1=new rectangle(15,20);
        s1.draw();
        System.out.println("Rectangle Area="+s1.getArea());
     
}
}

Output:

Circle Drawing
Circle Area=78.5
Rectangle Drawing
Rectangle Area=300.0

Here we can see, each method in the interface has a different implementation in the classes that implements that interface. The type of implementing method should exactly match with the method signature. We can also use the object of any class and give the type as interface type instead of class. (In this example, we have assigned circle and rectangle object to a shape type variable) Whenever we call any method using those objects, the correct version of the method will be called from the actual instance of the interface which is referred to there.

Multiple Inheritance in Java

As discussed earlier, Java doesn’t support multiple inheritances directly. But using the interface, we can achieve the same functionality.

If a class implements multiple interfaces or an interface extends multiple interfaces then, it is termed as multiple inheritances in Java.

Let us get more insights through the below example.

interface test1{  
void print();  
}  
interface test2{  
void show();  
}  
 
public class demo implements test1, test2{  
    
public void print()
{
    System.out.println("test1");
    
}  
public void show()
{
    System.out.println("test2");
    
}  
  
public static void main(String args[]){  
demo obj = new demo();  
obj.print();  
obj.show();  
 
    }  
}  

Output:

test1
test2

Key Points to remember about interfaces

  • One class can implement multiple interfaces. Class implementing interface must implement all the methods defined in the interface.
  • We cannot create an object of the interface. In technical words, interfaces cannot be instantiated.
  • However, interface reference can be used and pointed to a class implementing the interface.
  • Interface methods are implicitly public and abstract
  • Interface variables are public, static, and final by default.
  • An interface cannot implement another Interface. It can only extend another interface if needed.
  • An interface that is declared inside another interface is referred to as a nested interface
  • Interface variables need to be initialized while declaring them. If not, the compiler will give an error.
    • The below code snippet will throw an error as the variable i is not initialized with any value.

interface test
{
      int i;
}

  • No class can implement two interfaces which has the same method names but different return types.

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Core Java TrainingDec 24 to Jan 08View Details
Core Java TrainingDec 28 to Jan 12View Details
Core Java TrainingDec 31 to Jan 15View Details
Core Java TrainingJan 04 to Jan 19View Details
Last updated: 03 Apr 2023
About Author

I am Ruchitha, working as a content writer for MindMajix technologies. My writings focus on the latest technical software, tutorials, and innovations. I am also into research about AI and Neuromarketing. I am a media post-graduate from BCU – Birmingham, UK. Before, my writings focused on business articles on digital marketing and social media. You can connect with me on LinkedIn.

read less
  1. Share:
Java Articles