Interface
What is interface in Java?
Interface in java is core part of Java programming language and one of the way to achieve abstraction in Java along with abstract class. Even though interface is fundamental object oriented concept ; Many Java programmers thinks Interface in Java as advanced concept and refrain using interface from early in programming career. At very basic level interface in java is a keyword but same time it is an object oriented term to define contracts and abstraction , This contract is followed by any implementation of Interface in Java. Since multiple inheritance is not allowed in Java, interface is only way to implement multiple inheritance at Type level.
Example
Java interface example, java interface tutorialJava standard library itself has many inbuilt interfaces like Serializable, Clonnable, Runnable or Callable interface in Java. Declaring interface is easy but making it correct in first attempt is hard but if you are in business of designing API then you need to get it right in first attempt because its not possible to modify interface once it released without breaking all its implementation. here is an example of declaring interface in Java :
interface SessionIDCreator extends Serializable, Cloneable{
String TYPE = "AUTOMATIC";
int createSessionId();
}
class SerialSessionIDCreator implements SessionIDCreator{
private int lastSessionId;
@Override
public int createSessionId() {
return lastSessionId++;
}
}
In above example of interface in Java, SessionIDCreator
is an interface while SerialSessionIDCreator
is a implementation of interface.@Override
annotation can be used on interface method from Java 6 onwards, so always try to use it. Its one of those coding practice which should be in your code review checklist.