Java Interface : polymorphism and multiple inheritance

An interface is like an agreed-upon behavior between the classes and objects which we are created. Suppose you are a painter you are agreed upon doing the work related to painting , you cannot do the plumbing work right? It work the same way in Java and we bound or add a contract to the classes and objects to do specific type of work using an interface. It doesn't matter how you paint the wall , I mean the method to paint the wall may be different but all doing painting work.

So lets see what Java Interface has store in for us. It defines the set of method but it doesn't implement them, it also contains the constant declarations. A class which implements this interface must implement all the methods therefore agreeing for the specific behavior which interface decides.


Now lets see how interfaces helps in Multiple Inheritance and Polymorphism :

In the example below we can see the polymorphism as it is using a superclass variable to refer to a subclass object. The polymorphism in the below example is because of dynamic binding.Dynamic binding means the JVM will decide at runtime which method to invoke based on the class of the object , like at compile time it is not aware about which class's object need to be called , but at runtime because of dynamic binding it calls correct methods.


public interface Shapes {

public void draw();

}


public class Circle implements Shapes{

public void draw(){
System.out.println("Drawing a circle ...");
}

}


public class Square implements Shapes {

public void draw(){
System.out.println("Drawing a square");
}

}


public static void main( String[] args ){

Shapes circle = new Circle();
circle.draw();
Shapes square = new Square();
square.draw();
}



Drawing a circle ...
Drawing a square

Now lets see how Interface helps in having multiple inheritance, though having interface and having multiple inheritance is not same thing.
Because class implementing an interface doesn't have implementation of the interface methods also the can inherit the constants.
Classes which implement the same interface may or may not be related with each other or through the class hierarchy. Only thing is that an interface can have multiple superinterfaces which classes cant have.

But why we need interfaces :

1. As we can achieve polymorphism by dynamic binding , we can hide the class by revealing an object's programming interface.
2. We can capture the similarities between different classes without enforcing a class relationship.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment