Interface in Java | OOP Concept in Java
An interface in Java is a reference type, similar to a class, that contains only constants, method signatures, default methods, static methods, and nested types. Interfaces are used to achieve full abstraction and multiple inheritance in Java, allowing classes to implement several interfaces.
Key Points on Interface:
- An interface cannot contain any concrete (implemented) methods before Java 8.
- Since Java 8, interfaces can have
default
andstatic
methods with implementation. - All fields in an interface are implicitly
public
,static
, andfinal
. - A class can implement multiple interfaces, achieving multiple inheritance.
- Interfaces cannot have constructors since they are not classes.
- All methods in an interface are
public
andabstract
by default (except default and static methods introduced in Java 8). - Interfaces are implemented using the
implements
keyword, and a class must provide concrete implementations for all interface methods. - Interfaces define a contract that implementing classes must follow, promoting loose coupling and enhancing code flexibility.
Syntax of Interface:
Syntax Example
interface Animal {
void sound(); // Abstract method
}
Example of Interface in Java:
This example demonstrates an interface Animal
with an abstract method sound()
. The Dog
class implements the Animal
interface, providing its own implementation of the sound()
method.
Code Example
interface Animal {
void sound(); // Abstract method
}
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks.");
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Calls implemented method
}
}
Output
Dog barks.
Detailed Explanation:
- Abstract Method: An interface method is abstract by default and must be implemented by any concrete class implementing the interface.
- Default Methods: From Java 8 onwards, interfaces can contain default methods, which have a body and can be inherited by implementing classes.
- Static Methods: Java 8 also allows static methods in interfaces, which belong to the interface and can be called without an instance.
- Multiple Inheritance: A class can implement multiple interfaces, which is a way to achieve multiple inheritance in Java.
- Loose Coupling: Interfaces promote loose coupling by defining a contract that can be implemented by any class, allowing flexibility and modularity in code design.
Using interfaces effectively helps achieve full abstraction and makes code more flexible, as multiple classes can implement the same interface, adhering to a specific contract.