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");
cust.setAccount(acct);
cust.getAccount().deposit(100);
cust.getAccount().withdraw(960);
cust.getAccount().withdraw(2000);
}
}
|