I'm always excited to take on new projects and collaborate with innovative minds.
contact@niteshsynergy.com
https://www.niteshsynergy.com/
Java 8 Features: Default Methods & Static Methods in Interfaces
Java 8 Features: Default Methods & Static Methods in Interfaces
What is it? A default method in an interface allows you to add a method with a body (i.e., implementation) in the interface itself. This was introduced in Java 8 to avoid breaking existing implementations when new methods are added to an interface.
interface MyInterface {
default void myDefaultMethod() {
System.out.println("This is a default method");
}
}
Why is it needed?
Overriding Default Methods:
Yes, default methods can be overridden by a class that implements the interface.
interface Animal {
default void makeSound() {
System.out.println("Animal makes sound");
}
}
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
Real-World Use Case: In a gaming project, consider an interface Player
with a move()
method. If you later want to add a sprint()
method but want to avoid breaking existing player types (like Warrior
, Archer
, etc.), you can introduce a default implementation for sprint()
in the interface. This ensures backward compatibility with classes that don’t need the new feature while allowing others to override it as needed.
interface Player {
void attack();
default void sprint() {
System.out.println("Player is sprinting...");
}
}
class Warrior implements Player {
@Override
public void attack() {
System.out.println("Warrior attacks with a sword!");
}
}
class Archer implements Player {
@Override
public void attack() {
System.out.println("Archer attacks with a bow!");
}
}
What is it? A static method in an interface allows the interface to provide a utility method that doesn't depend on an instance of the implementing class. The method is invoked using the interface name, not an object.
interface MyInterface {
static void myStaticMethod() {
System.out.println("This is a static method");
}
}
Why is it needed?
Can We Override Static Methods?
interface MyInterface {
static void staticMethod() {
System.out.println("Static method in interface");
}
}
class MyClass implements MyInterface {
// Cannot override static methods from interface
// public static void staticMethod() { }
}
How Default Methods Help with Multiple Inheritance at the Class Level: Java doesn’t support multiple inheritance directly (i.e., a class cannot extend multiple classes), but it does allow a class to implement multiple interfaces. This can create issues if two interfaces provide conflicting default methods (known as the diamond problem in multiple inheritance scenarios). In such cases, the class must override the conflicting method.
Example of Diamond Problem: