...
From Java 8 onwards, interfaces can also contain default and static methods, thus allowing a limited form of behavior to be defined in interfaces themselves.
Demo - Tax Calculator Interface
Code Block |
---|
|
package Demo2Interface;
public interface TaxCalculator {
double calculateTax(double income);
}
|
Classes:
Code Block |
---|
|
package Demo2Interface;
public class TaxCalculator2023 implements TaxCalculator {
@Override
public double calculateTax(double income) {
return income * 0.2;
}
}
|
Code Block |
---|
|
package Demo2Interface;
public class TaxCalculator2024 implements TaxCalculator {
@Override
public double calculateTax(double income) {
return income * 0.25;
}
}
|
Driver:
Code Block |
---|
|
package Demo2Interface;
import java.text.NumberFormat; // Needed to format the currency
public class InterfaceMain {
public static void main(String[] args){
double myIncome = 30000.0;
double tax2023 = 0.0;
double tax2024 = 0.0;
TaxCalculator myTax2023 = new TaxCalculator2023();
TaxCalculator myTax2024 =new TaxCalculator2024();
NumberFormat formatter = NumberFormat.getCurrencyInstance();
System.out.println("Tax for year 2023 is " + formatter.format( myTax2023.calculateTax(myIncome) ));
System.out.println("Tax for year 2024 is " + formatter.format( myTax2024.calculateTax(myIncome) ));
} // end of Main
}//end of Class InterfaceMain
|
...