// 抽象クラス BankAccount
abstract class BankAccount {
// 抽象メソッド deposit を宣言
public abstract void deposit(double amount);
// 抽象メソッド withdraw を宣言
public abstract void withdraw(double amount);
}
// 具象クラス SavingsAccount
class SavingsAccount extends BankAccount {
private double balance;
// コンストラクタ
public SavingsAccount(double initialBalance) {
this.balance = initialBalance;
}
// deposit メソッドã®å®Ÿè£…
@Override
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
// withdraw メソッドã®å®Ÿè£…
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Insufficient funds for withdrawal.");
}
}
// 残高をå–å¾—ã™ã‚‹ãƒ¡ã‚½ãƒƒãƒ‰
public double getBalance() {
return balance;
}
}
// 具象クラス CheckingAccount
class CheckingAccount extends BankAccount {
private double balance;
// コンストラクタ
public CheckingAccount(double initialBalance) {
this.balance = initialBalance;
}
// deposit メソッドã®å®Ÿè£…
@Override
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
// withdraw メソッドã®å®Ÿè£…
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Insufficient funds for withdrawal.");
}
}
// 残高をå–å¾—ã™ã‚‹ãƒ¡ã‚½ãƒƒãƒ‰
public double getBalance() {
return balance;
}
}
// メインクラス
public class Main {
public static void main(String[] args) {
// SavingsAccount クラスã®åˆ©ç”¨ä¾‹
SavingsAccount savingsAccount = new SavingsAccount(1000);
savingsAccount.deposit(500);
savingsAccount.withdraw(200);
System.out.println("Savings Account Balance: $" + savingsAccount.getBalance());
// CheckingAccount クラスã®åˆ©ç”¨ä¾‹
CheckingAccount checkingAccount = new CheckingAccount(500);
checkingAccount.deposit(300);
checkingAccount.withdraw(800);
System.out.println("Checking Account Balance: $" + checkingAccount.getBalance());
}
}
ã“ã®ã‚³ãƒ¼ãƒ‰ã§ã¯ã€BankAccount ã‚¯ãƒ©ã‚¹ãŒæŠ½è±¡ãƒ¡ã‚½ãƒƒãƒ‰ deposit 㨠withdraw を宣言ã—ã¦ã„ã¾ã™ã€‚ãれを継承ã™ã‚‹å…·è±¡ã‚¯ãƒ©ã‚¹ SavingsAccount 㨠CheckingAccount ãŒã€ãれãžã‚Œã®éŠ€è¡Œå£åº§ã®å‹•作を実装ã—ã¦ã„ã¾ã™ã€‚Main クラスã§ãれãžã‚Œã®éŠ€è¡Œå£åº§ã‚’利用ã—ã¦ã€é 金や引ã出ã—ã®æ“作を行ã„ã€æ®‹é«˜ãŒè¡¨ç¤ºã•れる様åãŒç¤ºã•れã¦ã„ã¾ã™ã€‚
å‡ºåŠ›çµæžœï¼š
Deposited: $500
Withdrawn: $200
Savings Account Balance: $1300
Deposited: $300
Insufficient funds for withdrawal.
Checking Account Balance: $800
ãれãžã‚Œã®å£åº§ã«å¯¾ã—ã¦ã€é 金や引ã出ã—ã®æ“作ãŒè¡Œã‚ã‚Œã€æœ€çµ‚çš„ãªæ®‹é«˜ãŒè¡¨ç¤ºã•れã¦ã„ã¾ã™ã€‚
「016 抽象クラスã€å•題集リスト
🎯 実習ã§ç†è§£ã‚’æ·±ã‚よã†
ã“ã®å†…容ã«ã¤ã„ã¦JavaDrillã§å®Ÿéš›ã«æ‰‹ã‚’å‹•ã‹ã—ã¦å¦ç¿’ã§ãã¾ã™


コメント