Blog

Abstraction in Java

  • (4.0)
  • | 470 Ratings

Abstraction is basic concepts of Object Oriented Programming which revolve around the real-life entities.

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 any one 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 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 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 who implements the interface has the capability to implement that method.

Any number of class 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 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;
}

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 exists 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 whichever implements that interface. The type of implementing method should exactly match with 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, correct version of the method will be called from the actual instance of the interface which is referred there.

Multiple Inheritance in Java

As discussed earlier, Java doesn’t support multiple inheritances directly. But using 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 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 which is declared inside another interface is referred to as nested interface
  • Interface variables need to be initialized while declaring them. If not, the compiler will give an error.
    • Below code snippet will throw an error as variable i is not initialized with any value.

interface test
{
      int i;
}

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

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Ravindra Savaram
About The Author

Ravindra Savaram is a Content Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.


DMCA.com Protection Status

Close
Close