Default method
- The problem before Java 8 version: Class implement interface must provide implementation for all the method defined in that interface even though it doesn’t need to use all of them. You can imagine, a very large interface with hundred of methods, this problem can become very big challenge
- The default method is created to overcome this challenge. Default method is a method that has default implementaion define in the interface. And class implement implement that interface don’t have to provide their own implementation if it isn’t necessary
Example:
interface Greeting {
// Abstract method
String greet(String name);
// Default method
default String defaultGreet() {
return “Hello, World!”;
}
}
class GreetingImpl implements Greeting {
@Override
public String greet(String name) {
return “Hello, ” + name + “!”;
}
}
public class DefaultMethodExample {
public static void main(String[] args) {
Static method
- Static method is the same with default method and it can’t be override, from the class implement the interface.
- It is used to create utility methods inside a interface instead of create another utility class.
Example:
interface MathOperations {
// Abstract method
int add(int a, int b);
// Static method
static int multiply(int a, int b) {
return a * b;
}
}
class MathOperationsImpl implements MathOperations {
@Override
public int add(int a, int b) {
return a + b;
}
}
public class StaticMethodExample {
public static void main(String[] args) {
MathOperationsImpl mathOps = new MathOperationsImpl();
// Call abstract method
System.out.println(“Addition: ” + mathOps.add(5, 3)); // Output: Addition: 8
// Call static method
System.out.println(“Multiplication: ” + MathOperations.multiply(5, 3)); // Output: Multiplication: 15
}
}