- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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
- Related Articles
- What are Java methods equivalent to C# virtual functions?
- What are methods in Java?
- what are abstract methods in Java?
- What are generic methods in Java?
- What are vararg methods in Java?
- What are Default Methods in Java 8?
- What are Class/Static methods in Java?\n
- Are static methods inherited in Java?
- Static methods vs Instance methods in Java
- What are Hierarchical Methods?
- Methods in Java
- What are native methods in Java and where are they used?
- What is default, defender or extension method of Java 8?
- What are Event Methods in jQuery?
- What are async methods in JavaScript?
