Java Interfaces
An interface in Java is a blueprint of a class. It can have only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot be instantiated but they can be implemented by classes or extended by other interfaces.
![](https://cloudkeane.com/wp-content/uploads/2023/12/Java_interface-300x186.png)
What is an Java Interfaces ?
In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. They cannot be instantiated but can be implemented by classes or extended by other interfaces.
Example :
interface MyInterface {
void method1();
void method2();
}
Why use Java Interfaces ?
Interfaces are used to achieve abstraction and multiple inheritance in Java. They allow you to specify what a class must do, but not how it does it. They’re also used to achieve loose coupling.
Implementing an Interface
A class implements an interface by using the implements keyword. All methods in the interface must be implemented in the class.
Example :
class MyClass implements MyInterface {
public void method1() {
// Method implementation
}
public void method2() {
// Method implementation
}
}
Multiple Inheritance
Java does not support multiple inheritance with classes. However, multiple inheritance is supported with interfaces. A class can implement multiple interfaces.
Example :
interface FirstInterface {
void method1();
}
interface SecondInterface {
void method2();
}
class MyClass implements FirstInterface, SecondInterface {
public void method1() {
// Method implementation
}
public void method2() {
// Method implementation
}
}
Default Methods
From Java 8, interfaces can have default methods. These are methods with a default implementation. This allows you to add new methods to an interface without breaking existing implementations.
Example:
interface MyInterface {
default void defaultMethod() {
System.out.println(“This is a default method”);
}
}
Conclusion
Interfaces in Java are a fundamental concept that every Java programmer should understand. They provide a way to ensure that certain methods are implemented in classes, allow for multiple inheritance, and enable you to work with default and static methods.