What are defender methods or virtual methods in Java?



The default methods in an interface in Java are also known as defender methods or, virtual methods.

The defender/virtual methods are those that will have a default implementation in an interface. You can define defender/virtual methods using the default keyword as −

default void display() {    System.out.println("This is a default method"); }

There is no need to implement these defender/virtual methods in the implementing classes you can call them directly.

If you have an interface which is implemented by some classes and if you want to add a new method int it.

Then, you need to implement this newly added method in all the exiString classes that implement this interface. Which is a lot of work.

To resolve this, you can write a default/defender/virtual method for all the newly implemented methods.

Example

Following Java Example demonstrates the usage of the default method in Java.

 Live Demo

interface sampleInterface{    public void demo();    default void display() {       System.out.println("This is a default method");    } } public class DefaultMethodExample implements sampleInterface{    public void demo() {       System.out.println("This is the implementation of the demo method");    }    public static void main(String args[]) {       DefaultMethodExample obj = new DefaultMethodExample();       obj.demo();       obj.display();    } }

Output

This is the implementation of the demo method This is a default method
Updated on: 2020-06-29T14:10:49+05:30

716 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements