---
# System prepended metadata

title: mod08
tags: [C#]

---

```csharp
class Account
{
    private decimal _saving;

    public decimal Balance
    {
        get => default;
        set
        {
        }
    }

    public string Name
    {
        get => default;
        set
        {
        }
    }

    public void Deposit(decimal amount)
    {
        throw new System.NotImplementedException();
    }

    public void Withdraw(decimal amount)
    {
        throw new System.NotImplementedException();
    }
}
//======================================
//encapsulation
class Account
{
    private decimal _saving;

    public decimal Balance => _saving;


    public string Name { get; set; }

    public void Withdraw(decimal amount)
    {
        _saving -= amount;
    }
    public void Deposit(decimal amount)
    {
        _saving += amount;
    }
}

Account account = new Account();
account.Name = "Mary";
account.Deposit(1000);
account.Withdraw(700);
Console.WriteLine($"Name: {account.Name}, Balance: {account.Balance}");
//===========================
//inheritance
class SavingsAccount : Account
{
}

Account account = new Account();
account.Name = "Mary";
account.Deposit(1000);
account.Withdraw(700);
Console.WriteLine($"Name: {account.Name}, Balance: {account.Balance}");
Console.WriteLine("====================");
SavingsAccount account2 = new SavingsAccount();

account2.Name = "John";
account2.Deposit(1000);
account2.Withdraw(700);
Console.WriteLine($"Name: {account2.Name}, Balance: {account2.Balance}");
//===========================
class Account
{
    protected decimal _saving;
    public decimal Balance => _saving;
    public string Name { get; set; }
    public virtual void Withdraw(decimal amount)
    {
        _saving -= amount;
    }
    public void Deposit(decimal amount)
    {
        _saving += amount;
    }
}


class SavingsAccount : Account
{
    public string Demo { get; set; }

    public override void Withdraw(decimal amount)
    {
        if(_saving-amount<0)
        {
            Console.WriteLine("餘額不足，取款失敗");

        }else
        {
            base.Withdraw(amount);
        }
      
    }
}

Account account = new Account();
account.Name = "Mary";
account.Deposit(1000);
account.Withdraw(700);
account.Withdraw(500);
Console.WriteLine($"Name: {account.Name}, Balance: {account.Balance}");

Console.WriteLine("====================");
SavingsAccount account2 = new SavingsAccount();           
account2.Name = "John";
account2.Deposit(1000);
account2.Withdraw(700);
account2.Withdraw(500);
Console.WriteLine($"Name: {account2.Name}, Balance: {account2.Balance}");
//================================
//as 
//object obj = new object();
object obj = new SavingsAccount { Name = "Ken" };
//SavingsAccount account5 =(SavingsAccount) obj;
SavingsAccount account5 = obj as SavingsAccount;
Console.WriteLine($"Name: {account5?.Name}, Balance: {account5?.Balance}");


```