Java as an Object oriented programming language was invented in the early 90s.
In year 2005 , added major changes such as :
1.Enhanced for loops
2.Generics
3.Type-safe enumerations.
4.Annotations.
again after 10 years , in 2015 java 8 was introduced with lot of new features :
such as :1.Lambda Expressions
2.Method References
3.Default methods
4.New Stream API
5.New Date/Time API
6.Nashorn
-> now in java 8 ,interface introduced with some new changes.
interface can now define static methods.
interface can now define default methods.
package com.suv.java8; public class Java8Demo implements Calculator { public static void main(String[] args) { System.out.println("Welcome to https://www.crtr4u.com/"); Java8Demo jd = new Java8Demo(); jd.msgDisplay(); Calculator.sayHi(); } } interface Calculator { default void msgDisplay() { System.out.println("this is default method introduced in java 8 interface"); } static void sayHi() { System.out.println("Hi, this is static method allowed in interface from java 8"); } }
Output Welcome to https://www.crtr4u.com/ this is default method introduced in java 8 interface Hi, this is static method allowed in interface from java 8
-One Problem we must understand regarding default method in java 8 :
In Java , Multiple inheritance is not possible using classes
for example : class A extends B,C {} is not allowed in java
But , we can implement multiple interface
for example : class A implements InterfaceB , InterfaceC{}
Now problem is , what if both interface contain default method with same signature , look at below snapshot :
As shown , In above snapshot our both interfaces contain same method with same signature , now when AClass is implementing both interface InterfaceB and InterfaceC ,
we are getting error as :
Duplicate default methods named displayMsg with the parameters () and () are inherited from the types InterfaceC and InterfaceB
we can resolve above error as :
Way 1 : Overriding default method implementing class
forEach() is the default method of Iterable interface of java.lang package.
Example :
class Employee{
int empId;
String empName;
public Employee(int empId, String empName) {
super();
this.empId = empId;
this.empName = empName;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + "]";
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ForEachDemo {
public static void main(String[] args) {
List<Employee> empList=new ArrayList<Employee>();
empList.addAll(Arrays.asList(
new Employee(1,"Neel"),
new Employee(2,"Prashant"),
new Employee(3,"Jay"),
new Employee(4,"Jeet"),
new Employee(5,"RK")
));
empList.forEach(e->System.out.println(e));
}
}
Output :
Employee [empId=1, empName=Neel]
Employee [empId=2, empName=Prashant]
Employee [empId=3, empName=Jay]
Employee [empId=4, empName=Jeet]
Employee [empId=5, empName=RK]
Happy Learning,thanks for reading our article.