---
# System prepended metadata

title: 'polymorphism upcast , downcast'
tags: [java]

---



// Father Class
```java=
class BankAccount {
  private String accountNumber;
  private double balance;

  public BankAccount(String accountNumber, double balance) {
    this.accountNumber = accountNumber;
    this.balance = balance;
  }

  public String getAccountNumber() {
    return accountNumber;
  }

  public double getBalance() {
    return balance;
  }

  public void deposit(double amount) {
    balance += amount;
  }

  public void withdraw(double amount) {
    balance -= amount;
  }
}
```

// Child Class
```java=
public class CheckingAccount extends BankAccount {
  public CheckingAccount(String accountNumber, double balance) {
    super(accountNumber, balance);
  }

  double balance = super.getBalance();

  public void writeCheck(double amount) {
    if (balance < amount) {
      throw new RuntimeException();
    }

    balance -= amount;
  }
}

```
// Child Class
```java=
class SavingsAccount extends BankAccount {
  public SavingsAccount(String accountNumber, double balance) {
    super(accountNumber, balance);
  }
    
  double balance = super.getBalance();

  public void earnInterest() {
    balance += balance * 0.01;
  }
}
```

```graphviz
digraph hierarchy {

nodesep=0.5 // increases the separation between nodes
                
node [color=Red,fontname=Courier,shape=box] //All nodes will this shape and colour
edge [color=Blue, style=dashed] //All the lines look like this

        BankAccount->{CheckingAccount SavingsAccount} //BusinessManager}
               // Deputy1->{Teacher1 Teacher2}
               // BusinessManager->ITManager
               // {rank=same;getAccountNumber getBalance deposit withdraw} 
                 // Put them on the same level
}
```

// upcast
```java=
BankAccount account = new CheckingAccount("1234567890", 1000.00);
```
// downcast
```java=
CheckingAccount checkingAccount = (CheckingAccount) account;
checkingAccount.writeCheck(500.00);
```
// ClassCastException
```java=
BankAccount account = new SavingsAccount("1234567890", 1000.00);

CheckingAccount checkingAccount = (CheckingAccount) account; // 會發生 ClassCastException
```
// 留意事項
* 向上轉型可以安全地進行，因為所有Child Class都extend Father Class
* 向上轉型後，只能用Father class既method。
* 向下轉型只有在Father Class參考確實指向Child Class Object時才是安全的。
* 向下轉型後，可以用Child Class And Father Class 既method。

如果向下轉型時Father Class參考不指向Child Class物件，則會發生 ClassCastException。