Java Program to get Rate of interest of banks using interface Bank.
Objective
Write a Java program to fetch different Bank Interest Rates using a common Interface.
Algorithm / Approach
- Create an interface
Bankwith a methodpublic float roi();. - Create classes for
HDFC,PNB, andSBIthat all implement theBankinterface. - Each bank class should return its specific Rate of Interest (ROI) from the overridden
roi()method. - In main, use the
Bankinterface reference to sequentially instantiate the different banks and print their ROIs.
HDFC.java
interface Bank
{
public float roi();
}
class HDFC implements Bank {
public float roi() {
return 4.5f;
}
}
class PNB implements Bank {
public float roi() {
return 4.9f;
}
}
class SBI implements Bank {
public float roi() {
return 3.5f;
}
}
class Main {
public static void main(String[] a)
{
Bank b = new HDFC();
System.out.println("HDFC- "+b.roi());
Bank b2 = new PNB();
System.out.println("PNB- "+b2.roi());
Bank b3 = new SBI();
System.out.println("SBI- "+b3.roi());
}
}
Expected Output
HDFC- 4.5 PNB- 4.9 SBI- 3.5
Explanation of the Program
- This program is a classic example of polymorphism enabled by interfaces.
- The main program only needs to know about the
Bankinterface. It doesn't care *how* a specific bank calculates its ROI, only that it is guaranteed to have a method calledroi(). - This loose coupling makes the code highly scalable. Adding a new bank (like ICICI) requires zero changes to the main logic; you simply create a new class that implements the interface.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)