Method overriding to calculate simple interestCreate an abstract class Bank with method calculateSimpleInterest method which takes the amount of type double and time of type int (in years) as parameters and returns double type simple interest with interest at 6 PPA.
Create classes BankA, BankB and BankC which extends class Bank and override the method calculateSimpleInterest. Class BankA, BankB, and BankC calculate the interest at 10 PPA, 9 PPA, and 7 PPA respectively in an overridden method.
Input
1
45000
3
where,
Output
13500.00
where the output in 2 decimal numbers.
import java.util.Scanner;
public class Q178143 {
/**
* abstract class Bank
* @author Stavr
*
*/
public static abstract class Bank{
/**abstract
* method calculateSimpleInterest method which takes the amount of type double and time of type int (in years)
* as parameters and returns double type simple interest with interest at 6 PPA.
* @param principalAmount
* @param years
* @return
*/
public double calculateSimpleInterest(double principalAmount,int years) {
final double PPA=0.06;
return principalAmount*(1+PPA*years)-principalAmount;
}
}
public static class BankA extends Bank{
@Override
public double calculateSimpleInterest(double principalAmount,int years) {
final double PPA=0.1;
return principalAmount*(1+PPA*years)-principalAmount;
}
}
public static class BankB extends Bank{
@Override
public double calculateSimpleInterest(double principalAmount,int years) {
final double PPA=0.09;
return principalAmount*(1+PPA*years)-principalAmount;
}
}
public static class BankC extends Bank{
@Override
public double calculateSimpleInterest(double principalAmount,int years) {
final double PPA=0.07;
return principalAmount*(1+PPA*years)-principalAmount;
}
}
/**
* The start point of the program
*
* @param args
*/
public static void main(String[] args) {
// Create Scanner object
Scanner keyboard = new Scanner(System.in);
try {
// Get the input values
System.out.print("Select bank (1 for BankA, 2 for BankB and 3 for BankC): ");
int choice =keyboard.nextInt();
Bank selectedBank=null;
if(choice==1) {
selectedBank=new BankA();
}
if(choice==2) {
selectedBank=new BankB();
}
if(choice==3) {
selectedBank=new BankC();
}
System.out.print("Enter principal amount: ");
double principalAmount = keyboard.nextDouble();
System.out.print("Enter time in years: ");
int years =keyboard.nextInt();
if(selectedBank!=null) {
System.out.println("Simple interest: "+String.format("%.2f",selectedBank.calculateSimpleInterest(principalAmount, years)));
}else {
System.out.println("Select correct bank.");
}
} catch (Exception e) {
// Display error message
System.out.println(e.getMessage());
}
// close Scanner
keyboard.close();
}
}
Comments
Leave a comment