Close

Java 8 Default Methods - Default Method Examples

Java 8 Default Methods Java 

public interface Employee {

String getName();

String getDept();

BigDecimal getSalary();

default BigDecimal getBonus() {
return getSalary().multiply(new BigDecimal(0.10)).
setScale(2, BigDecimal.ROUND_HALF_UP);
}

default String getEmployeeInfo() {
return "Name: " + getName() +
", Dept: " + getDept() +
", Salary " + getSalary() +
", Bonus " + getBonus();
}

static String getEmployeeInfo(List<Employee> employeeList) {
String info = "";
for (Employee employee : employeeList) {
info += employee.getEmployeeInfo() + "\n";
}
return info;
}
}
Original Post




import java.math.BigDecimal;

public interface BonusCalculator {

BigDecimal getSalary();

BigDecimal getBonusPercent();

default BigDecimal getBonus() {
return getSalary().multiply(getBonusPercent())
.divide(new BigDecimal(100));
}
}
Original Post




public interface IEnum<E extends Enum<E>> {

int ordinal();

default E next() {
E[] ies = this.getAllValues();
return this.ordinal() != ies.length - 1 ? ies[this.ordinal() + 1] : null;
}

default E previous() {
return this.ordinal() != 0 ? this.getAllValues()[this.ordinal() - 1] : null;
}

@SuppressWarnings("unchecked")
private E[] getAllValues() {//java 9 private methods in interface
IEnum[] ies = this.getClass().getEnumConstants();
return (E[]) ies;
}
}
Original Post




See Also