OOP实验6-多态性

实验六 多态性

实验六 多态性
本实验4学时

1、实验目的:
重写继承来的函数, 实现多态性。

2、实验环境与条件:
JDK, Netbeans

3、实验内容:
在前一个实验的基础上, 利用类的多态性, 替换原有类中的某个功能.
程序具体的功能/作用, 自己设定.

内容参考示例:
文件Account.java

public class Account {
    private String accountID;
    private int balance;
    public void deposit(int amount) {
        this.balance += amount;
    }
    public void withdraw(int amount) {
        this.balance -= amount;
    }
    public Account(String accountID, int balance) {
        this.accountID = accountID;
        this.balance = balance;
    }
    public String getAccountID() {
        return accountID;
    }
    public int getBalance() {
        return balance;
    }
}

文件CCBAccount.java

public class CCBAccount extends Account {
    public CCBAccount(String accountID, int balance) {
        super(accountID, balance);
    }
    public void transfer(Account to, int amount) {
        if (amount < 0) {
            return;
        }
        if (this.getBalance() < amount) {
            return;
        }
        this.withdraw(amount);
        to.deposit(amount);
    }
    @Override
    public void deposit(int amount) {
        if (amount < 0) {
            return;
        }
        super.deposit(amount);
    }
    @Override
    public void withdraw(int amount) {
        if (amount < 0) {
            return;
        }
        if (this.getBalance() < amount) {
            return;
        }
        super.withdraw(amount);
    }
}

文件MainClass.java

public class MainClass {
    public static void main(String[] args) {
        CCBAccount account1 = new CCBAccount("6200001", 1000);
        account1.deposit(100);
        System.out.println(account1.getAccountID() + " : " + account1.getBalance());
        CCBAccount account2 = new CCBAccount("6200002", 1000);
        account2.withdraw(-100);
        System.out.println(account2.getAccountID() + " : " + account2.getBalance());
        account1.transfer(account2, 10000);
        System.out.println(account1.getAccountID() + " : " + account1.getBalance());
        System.out.println(account2.getAccountID() + " : " + account2.getBalance());
        account1.transfer(account2, -10000);
        System.out.println(account1.getAccountID() + " : " + account1.getBalance());
        System.out.println(account2.getAccountID() + " : " + account2.getBalance());
    }
}

你可能感兴趣的:(OOP)