JAvaベース_day0022_java_キーワード_Override__サブクラス_親_個人口座貯金_消費_テスト
2577 ワード
アカウントクラス:
子:親メソッドOverrideの書き換え
親をテストする方法
書き換え後のサブクラスのテスト方法
package day08_06;
public class Account {
private int id;
private double balance;
private double annualInterstRate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterstRate() {
return annualInterstRate;
}
public void setAnnualInterstRate(double annualInterstRate) {
this.annualInterstRate = annualInterstRate;
}
public Account(int id, double balance, double annualInterstRate) {
super();
this.id = id;
this.balance = balance;
this.annualInterstRate = annualInterstRate;
}
public Account() {
super();
}
//
public double getMonthlyInterest(){
return this.annualInterstRate/12;
}
//
public void withdraw(double amount){
if(this.balance>=amount){
this.balance-=amount;
}else{
System.out.println(" ");
}
}
//
public void deposit(double amount){
this.balance+=amount;
}
}
子:親メソッドOverrideの書き換え
package day08_06;
public class CheckAccount extends Account{
private double overdraft;
@Override
public void withdraw(double amount) {
if(amount super.getBalance()){
if((amount-super.getBalance()) > overdraft ){
System.out.println(" !");
}else{
this.overdraft-=(amount-super.getBalance());
super.setBalance(0);
}
}
}
public double getOverdraft() {
return overdraft;
}
public void setOverdraft(double overdraft) {
this.overdraft = overdraft;
}
}
親をテストする方法
package day08_06;
public class TestAccount {
public static void main(String[] args) {
Account acc = new Account(1000,20000,0.045);
acc.deposit(30000);
acc.withdraw(2000);
System.out.println(acc.getBalance());
}
}
書き換え後のサブクラスのテスト方法
package day08_06;
public class TestCheckAccount {
public static void main(String[] args) {
CheckAccount ca=new CheckAccount();
ca.setBalance(20000);
ca.setAnnualInterstRate(0.045);
ca.setId(1122);
ca.setOverdraft(5000);
ca.withdraw(5000);
System.out.println(ca.getBalance()+":- "+ca.getOverdraft());
ca.withdraw(18000);
System.out.println(ca.getBalance()+":- "+ca.getOverdraft());
ca.withdraw(3000);
System.out.println(ca.getBalance()+":- "+ca.getOverdraft());
}
}