// (named) local class
class EmpnoComparator implements Comparator<Employee> {
public int compare(Employee e1, Employee e2) {
return e1.getEmpno() - e2.getEmpno();
}
}
Arrays.sort(arr, new EmpnoComparator()); // anonymous obj of local class
// Anonymous inner class
Comparator<Employee> cmp = new Comparator<Employee>() {
public int compare(Employee e1, Employee e2) {
return e1.getEmpno() - e2.getEmpno();
}
};
Arrays.sort(arr, cmp);
// Anonymous object of Anonymous inner class.
Arrays.sort(arr, new Comparator<Employee>() {
public int compare(Employee e1, Employee e2) {
return e1.getEmpno() - e2.getEmpno();
}
});
interface Geometry {
/*public static final*/ double PI = 3.14;
/*public abstract*/ int calcRectArea(int length, int breadth);
/*public abstract*/ int calcRectPeri(int length, int breadth);
}
// By default fields of interface is public static final
// and methods are public abstract
Java 8 added many new features in interfaces in order to support functional programming in Java. Many of these features also contradicts earlier Java/OOP concepts.
interface Emp {
double getSal();
default double calcIncentives() {
return 0.0;
}
}
class Manager implements Emp {
// ...
// calcIncentives() is overridden
double calcIncentives() {
return getSal() * 0.2;
}
}
class Clerk implements Emp {
// ...
// calcIncentives() is not overridden -- so method of interface is considered
}
new Manager().calcIncentives(); // return sal * 0.2
new Clerk().calcIncentives(); // return 0.0