Introduction
Default methods let you add new behavior to interfaces without breaking old code.
Jump into concepts and practice - no test required
Default methods let you add new behavior to interfaces without breaking old code.
public interface InterfaceName { default void methodName() { // method body } }
Default methods have the default keyword before the return type.
They can have a body, unlike regular interface methods.
public interface Greeting { default void sayHello() { System.out.println("Hello!"); } }
public interface MathOperations { default int square(int x) { return x * x; } }
The Vehicle interface has a default start method. The Car class uses it without writing its own version.
public interface Vehicle { default void start() { System.out.println("Vehicle is starting"); } } public class Car implements Vehicle { // No need to override start() } public class Main { public static void main(String[] args) { Car myCar = new Car(); myCar.start(); } }
If a class implements two interfaces with the same default method, it must override it to avoid conflict.
Default methods help keep interfaces flexible and backward compatible.
Default methods let interfaces have method bodies.
They help add new features without breaking old code.
Classes can use or override default methods.
default methods in Java interfaces?default, followed by the return type, method name, and body.default void show() { ... }. Others have incorrect order or keywords.interface A {
default void greet() {
System.out.println("Hello from A");
}
}
class B implements A {
public void greet() {
System.out.println("Hello from B");
}
}
public class Test {
public static void main(String[] args) {
A obj = new B();
obj.greet();
}
}greet() method from interface A with its own implementation.interface X {
default void display() {
System.out.println("X display");
}
}
interface Y {
default void display() {
System.out.println("Y display");
}
}
class Z implements X, Y {
public void display() {
// ???
}
}display() method to fix the error?X.super.display() or Y.super.display().interface Printer {
default void print() {
System.out.println("Printing document");
}
}
interface Scanner {
default void print() {
System.out.println("Scanning document");
}
}
class MultiFunctionDevice implements Printer, Scanner {
public void print() {
// Combine both behaviors here
}
}print() correctly combines both default methods?InterfaceName.super.method().