Interface in Java

What is an Interface in Java

Interfaces has been the heart of most of the Java fundamentals and coding, mostly because there existence support Polymorphism, which is one of the four Principle of OOPS apart from Abstraction, Encapsulation and Inheritance.

Interface as the name suggests is a "Contract". Yes you read it right. It is contract between the interface provider and the interface implementer that the methods mentioned in the Interface will be implemented. Mostly Interfaces are used vis a vis Inheritance, and there is much research done before choosing one.

An Interface is like a pure abstract class, with the difference that the all the methods of the interface are abstract, so any class that implements this interface has to implement all the methods mentioned in this interface. That's the law. So actually the interface tells that which methods are to be implemented, but not that how we are going to implement. It is left for the subclasses to decide how to implement this.

One important part of Java is that it supports multiple Implementations, but not multiple Inheritance. So a subclass can implement multiple Interfaces, but cannot extend multiple classes. I will detail on this in a later post where I will tell you that if multiple Inheritance is allowed, then how it may lead to the Deadly Diamond of death. Anyhow that's a bit deviating from the main topic. Our primary concern are the Interfaces.

An example of an Interface is shown below:-

////////////////////////////////////////////

Interface JavaTest{
public static final int val = 3;

public abstract doTest();
public abstract takeResult();
}

////////////////////////////////////////////

Here in this Interface declaration file, the keywords public and abstract are not required for the methods as they are implicit. Moreover the keywords for the variable declared in the Interface are also not required as they are also implicit. 

So any variable declared in an Interface is practically a constant, and all the methods which are declared in the interface have to be implemented by the first concrete subclass that implements this interface.




There is one key point regarding the Interfaces, and that is you cannot declare the methods of the Interface to be final. Remember that final methods cannot be overridden, and an abstract method is useless if we do not override it. That is the main reason that abstract and final are never used together for any method.