Pattern Matching for instanceof
is a feature introduced in Java 17 that simplifies the process of type checking and casting. This feature allows you to perform these operations in a more concise and readable manner.
In this example, we'll define a common interface for accounts, create specific implementations for different account types, and then use pattern matching to perform operations based on the account type.
public interface BankAccount {
void displayAccountDetails();
double getBalance();
}
public class SavingsAccount implements BankAccount {
private double balance;
private double interestRate;
public SavingsAccount(double balance, double interestRate) {
this.balance = balance;
this.interestRate = interestRate;
}
@Override
public void displayAccountDetails() {
System.out.println("Savings Account: Balance = " + balance + ", Interest Rate = " + interestRate);
}
@Override
public double getBalance() {
return balance;
}
}
public class CurrentAccount implements BankAccount {
private double balance;
public CurrentAccount(double balance) {
this.balance = balance;
}
@Override
public void displayAccountDetails() {
System.out.println("Current Account: Balance = " + balance);
}
@Override
public double getBalance() {
return balance;
}
}
public class LoanAccount implements BankAccount {
private double loanAmount;
private double interestRate;
public LoanAccount(double loanAmount, double interestRate) {
this.loanAmount = loanAmount;
this.interestRate = interestRate;
}
@Override
public void displayAccountDetails() {
System.out.println("Loan Account: Loan Amount = " + loanAmount + ", Interest Rate = " + interestRate);
}
@Override
public double getBalance() {
return -loanAmount; // Negative balance to represent debt
}
}
import java.util.ArrayList;
import java.util.List;
public class BankingApplication {
public static void main(String[] args) {
// Create a list of bank accounts
List<BankAccount> accounts = new ArrayList<>();
accounts.add(new SavingsAccount(1000, 2.5));
accounts.add(new CurrentAccount(1500));
accounts.add(new LoanAccount(5000, 5.0));
// Process each account
for (BankAccount account : accounts) {
// Using pattern matching for instanceof
if (account instanceof SavingsAccount savings) {
savings.displayAccountDetails();
System.out.println("Annual Interest: " + (savings.getBalance() * savings.interestRate / 100));
} else if (account instanceof CurrentAccount current) {
current.displayAccountDetails();
System.out.println("Current account balance is usable for transactions.");
} else if (account instanceof LoanAccount loan) {
loan.displayAccountDetails();
System.out.println("Outstanding loan amount: " + loan.getBalance());
}
}
}
}
ClassCastException
is eliminated.Using pattern matching for instanceof
in a banking application allows for cleaner and safer code, especially when dealing with various types of objects that share a common interface.