Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:53:46 Viewed : 233
Default methods in Java are methods declared in an interface with a default implementation. They allow you to add new methods to interfaces without breaking the classes that already implement those interfaces. Here is the syntax and usage of default methods:
javapublic interface MyInterface {
// Abstract method (mandatory for interfaces)
void abstractMethod();
// Default method with a default implementation
default void defaultMethod() {
// Default implementation
System.out.println("Default method implementation");
}
}
defaultMethod
is a default method in the MyInterface
interface.Implementing the Interface:
javapublic class MyClass implements MyInterface {
@Override
public void abstractMethod() {
// Implementation of the abstract method
System.out.println("Implementation of abstractMethod");
}
// Default method is inherited, but can be overridden
@Override
public void defaultMethod() {
// Custom implementation of the default method
System.out.println("Custom implementation of defaultMethod");
}
}
Calling Default Method:
javaMyInterface myObject = new MyClass();
myObject.abstractMethod(); // Calls the overridden abstract method
myObject.defaultMethod(); // Calls the overridden default method
Inheriting Default Method:
javapublic class AnotherClass implements MyInterface {
@Override
public void abstractMethod() {
// Implementation of the abstract method
System.out.println("Implementation of abstractMethod");
}
}
In this case, AnotherClass
inherits the default implementation of defaultMethod
from the MyInterface
interface.
javapublic interface Calculator {
double add(double a, double b);
default double subtract(double a, double b) {
return a - b;
}
default double multiply(double a, double b) {
return a * b;
}
}
public class BasicCalculator implements Calculator {
@Override
public double add(double a, double b) {
return a + b;
}
// No need to override subtract or multiply, as they have default implementations
}
public class CalculatorApp {
public static void main(String[] args) {
BasicCalculator calculator = new BasicCalculator();
double sum = calculator.add(5, 3); // Result: 8.0
double difference = calculator.subtract(5, 3); // Result: 2.0
double product = calculator.multiply(5, 3); // Result: 15.0
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
}
}
In this example, the Calculator
interface defines an add
method and provides default implementations for subtract
and multiply
. The BasicCalculator
class implements the add
method and inherits the default implementations of subtract
and multiply
. The CalculatorApp
class demonstrates the usage of the calculator.