Java default methods allow you to define methods with a body inside an interface. They were introduced in Java 8.
In this chapter, you will learn about Java Default Methods, how they work, how to create them, and their syntax.
A default method is a method defined inside an interface with a complete implementation. It is a non-abstract method and is declared using the default keyword. Before Java 8, interfaces could only contain abstract methods, and implementing classes had to provide their implementation.
A default method is created inside an interface by using the default keyword followed by the method definition. The default method helps in adding new methods to interfaces without breaking existing code.
The syntax to define a default method is as follows:
Before Java 8:
With Default Methods:
Let’s understand how a default method works in an interface with the help of an example.
Output:
Greetings! Hello from default method!
If a class implements two interfaces that have the same default method, it must override that method to resolve ambiguity.
This example demonstrates how to resolve ambiguity when multiple interfaces provide the same default method.
In the above program, we have defined two interfaces, A and B. Both have the show() default method. The class C implements both interfaces, which creates ambiguity because Java does not know which show() method to inherit.
To resolve this ambiguity, class C overrides the show() method and explicitly calls one of the interface methods using A.super.show() or B.super.show().
If A.super.show() is invoked, the output will be:
A's default
If B.super.show() is invoked, the output will be:
B's default
We can also define static methods inside an interface. Static methods are used to define utility methods and can be called using the interface name.
This example demonstrates how to define and use static methods inside an interface.
Output:
Hello, this is default method. This is abstract method. This is static method.
After the introduction of default and static methods in interfaces, they became more powerful. However, interfaces and abstract classes are still different. One key difference is that abstract classes can have constructors, whereas interfaces cannot.
This example demonstrates the use of constructors, abstract methods, and static methods in an abstract class.
Output:
You can create constructor in abstract class Addition: 30 Subtraction: 10 Multiplication: 200
We request you to subscribe our newsletter for upcoming updates.