An interface in Java is a reference type that defines a set of abstract methods that a class must implement. Interfaces provide a way to achieve abstraction and multiple inheritance in Java. They act as a contract that a class must adhere to, specifying what methods must be implemented but not how they are implemented.
Syntax of an Interface
interface InterfaceName {
// constant variables
int CONSTANT_VALUE = 100;
// abstract methods
void method1();
void method2();
}
Code language: JavaScript (javascript)
-
Interface Keyword: The
interface
keyword is used to declare an interface. -
Methods: All methods in an interface are implicitly
public
andabstract
unless declared as default or static. -
Constants: Variables in interfaces are implicitly
public
,static
, andfinal
.
Implementing an Interface
A class implements an interface using the implements
keyword:
class ImplementingClass implements InterfaceName {
public void method1() {
System.out.println("Method1 implementation");
}
public void method2() {
System.out.println("Method2 implementation");
}
}
Code language: PHP (php)
Example Program – Bank Transaction System
In this example, we will define an interface Transaction
and implement it in Deposit
and Withdrawal
classes:
interface Transaction { void execute(); } class Deposit implements Transaction { private double amount; public Deposit(double amount) { this.amount = amount; } public void execute() { System.out.println("Depositing: $" + amount); } } class Withdrawal implements Transaction { private double amount; public Withdrawal(double amount) { this.amount = amount; } public void execute() { System.out.println("Withdrawing: $" + amount); } } public class BankTransactionSystem { public static void main(String[] args) { Transaction deposit = new Deposit(500); Transaction withdrawal = new Withdrawal(200); deposit.execute(); withdrawal.execute(); } } /* Depositing: $500.0 Withdrawing: $200.0 */
Interfaces play a crucial role in Java by defining a contract that a class must adhere to without dictating the specific implementation details. They enable multiple inheritance, promote loose coupling, and establish a blueprint for achieving polymorphism and abstraction. By implementing interfaces, classes can standardize their behavior while maintaining flexibility in how the methods are executed. Java 8 and subsequent versions further enhance interfaces with the inclusion of default and static methods, allowing developers to provide method bodies within interfaces.