An Interface in Java is an abstract type that defines a set of methods a class must implement.
- An interface acts as a contract that specifies what a class should do, but not how it should do it. It is used to achieve abstraction and multiple inheritance in Java. We define interfaces for capabilities (e.g., Comparable,
Serializable,Drawable). - A class that implements an interface must implement all the methods of the interface. Only variables are public static final by default.
- Before Java 8, interfaces could only have abstract methods (no bodies). Since Java 8, they can also include default and static methods (with implementation) and since Java 9, private methods are allowed.
This example demonstrates how an interface in Java defines constants and abstract methods, which are implemented by a class.
import java.io.*;
// Interface Declared
interface testInterface {
// public, static and final
final int a = 10;
// public and abstract
void display();
}
// Class implementing interface
class TestClass implements testInterface {
// Implementing the capabilities of Interface
public void display(){
System.out.println("Geek");
}
}
class Geeks{
public static void main(String[] args){
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
Output
Geek 10
Notes:
- Private methods can only be called inside default or static methods.
- Static methods are accessed using the interface name, not via objects.
- To implement an interface, use the implements keyword.
Relationship Between Class and Interface
A class can extend another class and similarly, an interface can extend another interface. However, only a class can implement an interface and the reverse (an interface implementing a class) is not allowed.