- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Java 8 default methods in interfaces
Java 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8.
For example, ‘List’ or ‘Collection’ interfaces do not have ‘forEach’ method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same.
Example
public class Java8Tester { public static void main(String args[]) { Vehicle vehicle = new Car(); vehicle.print(); } } interface Vehicle { default void print() { System.out.println("I am a vehicle!"); } static void blowHorn() { System.out.println("Blowing horn!!!"); } } interface FourWheeler { default void print() { System.out.println("I am a four wheeler!"); } } class Car implements Vehicle, FourWheeler { public void print() { Vehicle.super.print(); FourWheeler.super.print(); Vehicle.blowHorn(); System.out.println("I am a car!"); } }
Output
I am a vehicle! I am a four wheeler! Blowing horn!!! I am a car!
- Related Articles
- Java 8 static methods in interfaces
- What are Default Methods in Java 8?
- Private Methods in Java 9 Interfaces
- Default methods in Java
- Can interfaces have Static methods in Java?
- Can we override default methods in Java?
- What is the use of default methods in Java?
- How to solve diamond problem using default methods in Java
- Interfaces in Java
- How to solve the diamond problem using default methods in Java?
- What happens if we overload default methods of an interface in java?
- Difference between default and static interface method in Java 8.
- Callback using Interfaces in Java
- Evolution of interfaces in Java
- Functional Interfaces in Java Programming

Advertisements