Defaultmethods in Java
In Java, a default method is a method that is defined in an interface and has a default implementation. Default methods were introduced in Java 8 as a way to add new functionality to existing interfaces without breaking compatibility with existing code.
Here is an example of a default method in Java:
public interface MyInterface {
void doSomething();
default void doSomethingElse() {
// default implementation
}
}
In this example, the MyInterface
interface has two methods: doSomething()
, which is an abstract method with no implementation, and doSomethingElse()
, which is a default method with a default implementation.
A class that implements the MyInterface
interface can override the default implementation of doSomethingElse()
if it needs to provide a custom implementation:
public class MyClass implements MyInterface {
@Override
public void doSomething() {
// custom implementation
}
@Override
public void doSomethingElse() {
// custom implementation
}
}
Alternatively, if the class does not override the default implementation of doSomethingElse()
, it will use the default implementation provided by the interface:
public class MyClass implements MyInterface {
@Override
public void doSomething() {
// custom implementation
}
}
MyClass obj = new MyClass();
obj.doSomethingElse(); // uses the default implementation
Default methods allow you to add new functionality to an interface without breaking compatibility with existing code.
Here's an example of how default methods can be used to add new functionality to an existing interface:
public interface MyInterface {
void doSomething();
default void doSomethingElse() {
// default implementation
}
}
In this example, the MyInterface
interface has a default method, doSomethingElse()
, which provides a default implementation. This means that any class that implements the MyInterface
interface will have access to the doSomethingElse()
method, even if the class was written before the doSomethingElse()
method was added to the interface.
This allows you to add new functionality to the MyInterface
interface without breaking compatibility with existing code that implements the interface. The existing code will continue to work as expected, and any new code that implements the interface will also have access to the new functionality provided by the default method.
It's worth noting that default methods can be overridden by a class that implements the interface, if the class needs to provide a custom implementation of the default method. This allows you to customize the behavior of the default method for specific classes, while still taking advantage of the default implementation provided by the interface.