fork download
  1. abstract class Account {
  2. protected int accountNumber;
  3. protected double balance;
  4.  
  5. public Account(int accountNumber) {
  6. this.accountNumber = accountNumber;
  7. this.balance = 0.0;
  8. }
  9.  
  10. public void setBalance(double balance) {
  11. this.balance = balance;
  12. }
  13.  
  14. public abstract int getAccountNumber();
  15. public abstract double getBalance();
  16. }
  17.  
  18. class Checking extends Account {
  19.  
  20. public Checking(int accountNumber) {
  21. super(accountNumber);
  22. }
  23.  
  24. @Override
  25. public int getAccountNumber() {
  26. return accountNumber;
  27. }
  28.  
  29. @Override
  30. public double getBalance() {
  31. return balance;
  32. }
  33.  
  34. public void display() {
  35. System.out.println("Checking Account Information " + accountNumber + " $" + balance);
  36. }
  37. }
  38.  
  39. class Savings extends Account {
  40. private double interestRate;
  41.  
  42. public Savings(int accountNumber, double interestRate) {
  43. super(accountNumber);
  44. this.interestRate = interestRate;
  45. }
  46.  
  47. @Override
  48. public int getAccountNumber() {
  49. return accountNumber;
  50. }
  51.  
  52. @Override
  53. public double getBalance() {
  54. return balance;
  55. }
  56.  
  57. public void display() {
  58. System.out.println("Savings Account Information " + accountNumber + " $" + balance + " rate " + interestRate);
  59. }
  60. }
  61.  
  62. public class Main {
  63. public static void main(String[] args) {
  64. Account[] accounts = new Account[10];
  65.  
  66. for (int i = 0; i < accounts.length; i++) {
  67. int accNum = 101 + i;
  68. if (i % 2 == 0) {
  69. accounts[i] = new Checking(accNum);
  70. } else {
  71. double rate = 2.0 + (i * 0.1);
  72. accounts[i] = new Savings(accNum, rate);
  73. }
  74. }
  75.  
  76. for (Account acc : accounts) {
  77. if (acc instanceof Checking) {
  78. ((Checking) acc).display();
  79. } else if (acc instanceof Savings) {
  80. ((Savings) acc).display();
  81. }
  82. }
  83. }
  84. }
  85.  
Success #stdin #stdout 0.2s 58960KB
stdin
Standard input is empty
stdout
Checking Account Information 101 $0.0
Savings Account Information 102 $0.0 rate 2.1
Checking Account Information 103 $0.0
Savings Account Information 104 $0.0 rate 2.3
Checking Account Information 105 $0.0
Savings Account Information 106 $0.0 rate 2.5
Checking Account Information 107 $0.0
Savings Account Information 108 $0.0 rate 2.7
Checking Account Information 109 $0.0
Savings Account Information 110 $0.0 rate 2.9