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

2023-11-15

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);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 一个类作为另外一个类的属性 的相关文章

随机推荐