Skip to main content

ProwessApps

Learn · Practice · Excel

Create a class Account which has method interest() to calculate simple interest and override this method in derive class SavingAccount, which calculate compound interest.

Java Code Example — Polymorphism Programs

ADVERTISEMENT

Create a class Account which has method interest() to calculate simple interest and override this method in derive class SavingAccount, which calculate compound interest.

Objective

Demonstrate Runtime Polymorphism (Method Overriding) by calculating different types of bank interest.

Algorithm / Approach

  1. Create a parent class Account with an interest() method that calculates Simple Interest (P*R*T/100).
  2. Create a child class SavingAccount that extends Account.
  3. Override the interest() method in the child class to calculate Compound Interest instead.
  4. In main, instantiate Account and call interest().
  5. Then, instantiate SavingAccount and call interest() to see the overridden behavior.
Account.java
import java.util.Scanner;
class Account {
 String name;
 int amt,t,r;
 double si;
 public void input() {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Name: ");
  name = s.nextLine();
  System.out.print("Enter Amount: ");
  amt = s.nextInt();
  System.out.print("Enter Year: ");
  t = s.nextInt();
  System.out.print("Enter Rate: ");
  r = s.nextInt();
 }
 public void interest() {
  si = amt*t*r/100.0;
  System.out.println("Interest = "+si);
 }
}
class SavingAccount extends Account {
 public void interest() {
  si = amt*Math.pow((100+r)/100.0,t);
  si =si-amt;
  System.out.println("Interest = "+si);
 }
}
class Main {
 public static void main(String[] a)
 {
 System.out.println("Simple Account");
 Account ac=new Account();
 ac.input();
 ac.interest();
 Account ac2 = new SavingAccount();
 System.out.println("Saving Account");
 ac2.input();
 ac2.interest();
 }
}

Expected Output

Simple Account
Enter Name: Alok
Enter Amount: 2000
Enter Year: 3
Enter Rate: 10
Interest = 600.0
Saving Account
Enter Name: Deepak
Enter Amount: 2000
Enter Year: 3
Enter Rate: 10
Interest = 662.0000000000009

Explanation of the Program

  • Method Overriding occurs when a child class provides a specific implementation for a method that is already defined in its parent class.
  • Unlike overloading (which happens at compile-time), overriding is a form of runtime polymorphism (Dynamic Method Dispatch).
  • If you call interest() on a SavingAccount object, Java ignores the parent's Simple Interest logic entirely and executes the child's Compound Interest logic.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT