Java 一个类作为另外一个类的属性

Java中一个类的对象作为另外一个类的属性

Account 类


public class Account {
    public int id;// 账号
    private double balance; //余额
    private double annualInterestRest; // 年利率

    // 构造方法
    public  Account(int id, double balance, double annualInterestRest) {
        this.id = id;
        this.balance = balance;
        this.annualInterestRest = annualInterestRest;

    }
    // 取钱
    public void withdraw(double amount) {
        if (balance < amount) {
            System.out.println("鱼儿不足取款失败");
            return;
        }
        balance -= amount;
        System.out.println("成功取款,余额为: " + balance);

    }
    //存钱
    public void deposit(double amount) {
        balance += amount;
        System.out.println("存入成功,余额为:"+ balance);
    }
}

Customer类中的一个属性为Account的对象

public class Customer {
    private Account account;
    private String firstName;
    private String lastName;

    public Customer(String f,String l) {
        this.firstName = f;
        this.lastName = l;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

}

通过Customer 对象调用Account对象的方法

public class CustomerTest {
    public static void main(String[] args) {
        // 创建一个账户对象,并给这个账号里面设置钱
        Account acct = new Account(1000, 2000, 0.0123);

        Customer cust = new Customer("Jane","Smith");
        // 给 crust 这个人 给了一个账号,传入了一个账户对象
        cust.setAccount(acct);
        // cust.getAccount() 获取私有对象
        cust.getAccount().deposit(100);
        cust.getAccount().withdraw(960);
        cust.getAccount().withdraw(2000);
    }
}
  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值