Object-Oriented Programming (OOP) Interface: In languages like Java, C#, or TypeScript, an interface is a description of the actions that an object can do. It's a contract that classes adhere to, defining a set of methods that the classes must implement. This promotes a structure known as "programming to an interface", not an implementation, which enhances code modularity and flexibility.
In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types.
Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. An interface essentially defines a contract for behavior that a class can implement. The main purpose of an interface is to enable polymorphism in Java.
It's important to note that a class can implement multiple interfaces in Java. This is beneficial as Java does not support multiple inheritance, which means a class cannot inherit from more than one class. However, by using interfaces, you can achieve a similar effect, allowing a class to adhere to multiple sets of behavior as defined by multiple interfaces.
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
package Demo2Interface; public interface TaxCalculator { double calculateTax(double income); }
Classes:
package Demo2Interface; public class TaxCalculator2023 implements TaxCalculator { @Override public double calculateTax(double income) { return income * 0.2; } }
package Demo2Interface; public class TaxCalculator2024 implements TaxCalculator { @Override public double calculateTax(double income) { return income * 0.25; } }
Driver:
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