0
0
Javaprogramming~5 mins

Default methods in Java

Choose your learning style9 modes available
Introduction

Default methods let you add new behavior to interfaces without breaking old code.

You want to add a new method to an interface but keep old classes working.
You want to provide a common method implementation that many classes can share.
You want to avoid writing the same method code in every class that implements an interface.
Syntax
Java
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.

Examples
This interface has a default method that prints a greeting.
Java
public interface Greeting {
    default void sayHello() {
        System.out.println("Hello!");
    }
}
This default method returns the square of a number.
Java
public interface MathOperations {
    default int square(int x) {
        return x * x;
    }
}
Sample Program

The Vehicle interface has a default start method. The Car class uses it without writing its own version.

Java
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();
    }
}
OutputSuccess
Important Notes

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.

Summary

Default methods let interfaces have method bodies.

They help add new features without breaking old code.

Classes can use or override default methods.