Module-3
Module-3
Interface
An interface is declared using the interface keyword and typically contains method signatures
without implementations. Since Java 8, interfaces can also include default and static methods
with implementations.
Example
public interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method
default void run() { // Default method
System.out.println("Running...");
}
static void breathe() { // Static method
System.out.println("Breathing...");
}
}
Implementing an Interface
A class implements an interface using the implements keyword and provides concrete
implementations for all abstract methods.
@Override
public void swim() {
System.out.println("Duck is swimming.");
}
}
Here, the Duck class implements both Flyable and Swimmable interfaces, providing
implementations for both fly and swim methods.
Types of Interfaces
1. Functional Interface: An interface with exactly one abstract method. Used primarily
with lambda expressions.
Syntax
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
2. Marker Interface: An interface with no methods or fields. Used to mark a class for a
specific behavior.
Syntax
interface Serializable {}
Key Characteristics
Abstraction: Interfaces allow you to define methods that must be implemented,
hiding the implementation details.
Multiple Inheritance: A class can implement multiple interfaces, allowing for
multiple inheritance of types.
Polymorphism: Interfaces enable objects to be treated as instances of their interface
rather than their actual class.
Default and Static Methods: Since Java 8, interfaces can have default and static
methods with implementations.
Private Methods: Since Java 9, interfaces can have private methods to encapsulate
code used by default methods.
Interfaces Vs abstract classes
In Java, both interfaces and abstract classes are tools for achieving abstraction, but they
serve different purposes and have distinct characteristics. Here's a comprehensive comparison
to help you understand their differences and decide when to use each:
interface Y {
void methodY();
}
interface Z extends X, Y {
void methodZ();
}
class MyClass implements Z {
public void methodX() {
System.out.println("Method X");
}
public void methodY() {
System.out.println("Method Y");
}
public void methodZ() {
System.out.println("Method Z");
}
}
Handling Method Conflicts
When multiple interfaces being extended have methods with the same signature, and at least
one provides a default implementation, the compiler requires the implementing class to
override the method to resolve the conflict.
interface A {
default void greet() {
System.out.println("Hello from A");
}
}
interface B {
default void greet() {
System.out.println("Hello from B");
}
}
class MyClass implements A, B {
public void greet() {
A.super.greet(); // or B.super.greet();
}
}
In this scenario, MyClass must override the greet() method to resolve the ambiguity between
interfaces A and B.