JAVA继承练习——重写父类方法与super关键字之银行利息编程例题

//bank.java--父类
public class bank{
int savedMoney;
int year;
double interest;
double interestRate=0.29;
public double computerInterest(){
interest=year*interestRate*savedMoney;
return interest;
}
public void setInterestRate(double rate){
interestRate=rate;
}
}

~
~
~
~
~
~
~
~
~
~
"bank.java" 14L, 246C
//construction.java
public class constructionBank extends bank{
double year;
public double computerInterest(){
super.year=(int)year;
double r=year-(int)year;
int day=(int)(r*1000);
double yearInterest=super.computerInterest();
double dayInterest=day*0.0001*savedMoney;
interest=yearInterest+dayInterest;
System.out.printf("建设银行存款利息为:%f\n",interest);
return interest;
}
}


~
~
~
~
~
~
~
~
~
"constructionBank.java" 15L, 367C
//guangzhouBank.java
public class guangzhouBank extends bank{
double year;
public double computerInterest(){
super.year=(int)year;//调用父类变量year并赋值,如果这里不调用并赋值,下面调用父类方法computerInterest()时>因为利用的是父类中的变量year,计算返回得到的yearInterest的值将是0,因为year系统默认赋值0.
double r=year-(int)year;
int day=(int)(r*1000);
double yearInterest=super.computerInterest();
double dayInterest=day*0.00012*savedMoney;
interest=yearInterest+dayInterest;
System.out.printf("广州银行存款利息为:%f\n",interest);
return interest;
}
}

~
~
~
~
~
~
~
~
~
"guangzhouBank.java" 14L, 606C
//saveMoneyMain.java
import java.util.Scanner;
public class saveMoneyMain{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
constructionBank bank1=new constructionBank();
guangzhouBank bank2=new guangzhouBank();
System.out.println("请输入存款金额:");
bank1.savedMoney=bank2.savedMoney=sc.nextInt();
System.out.println("请输入存款年限:");
bank1.year=bank2.year=sc.nextDouble();
bank1.setInterestRate(0.035);
bank2.setInterestRate(0.035);
double interest1=bank1.computerInterest();
double interest2=bank2.computerInterest();
System.out.printf("两银行相差利息金额为:%f\n",interest2-interest1);
}
}

结果:

请输入存款金额:
8000
请输入存款年限:
8.236
建设银行存款利息为:2428.800000
广州银行存款利息为:2466.560000
两银行相差利息金额为:37.760000



你可能感兴趣的:(JAVA学习)