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());
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值