gpt4 book ai didi

java - java中如何让对象相互交互?

转载 作者:行者123 更新时间:2023-12-03 23:14:31 25 4
gpt4 key购买 nike

我最近开始学习java。这可能是一个愚蠢的问题,但是是否可以创建一个将余额从“firstAccount”对象转移到“secondAccount”对象的方法?

public class SavingsAccount{
int balance;

public SavingsAccount(String name, int balance){
this.balance = balance;
this.name = name;
}

public static void main(String[] args){
SavingsAccount firstAccount = new SavingsAccount("A", 5000);
SavingsAccount secondAccount = new SavingsAccount("B", 3000);
}
}

我想到的最好的是这个,

public void transfer(int amountToTransfer){
firstAccount.balance += amountToTransfer;
secondAccount.balance -= amountToTransfer;
}

当然它不起作用。我该如何解决?
提前致谢!

最佳答案

您可以将其设为一个static 方法,要求您传递要使用的两个帐户(您可以随意命名变量),或者制作一个需要一个帐户的非静态方法作为使用实例时的参数。

这是 static 变体:

public static void transfer(int amountToTransfer, SavingsAccount toAccount, SavingsAccount fromAccount){
toAccount.balance += amountToTransfer;
fromAccount.balance -= amountToTransfer;
}

这将在 static 上下文中使用,例如 main,并且将使用 YourClass.transfer(yourAmount, firstAccount, secondAccount).

这是在您的 SavingsAccount 类中的非静态变体,您可以决定转移到实例或从实例转移是否更有意义:

public void transfer(int amountToTransfer, SavingsAccount toAccount){
toAccount.balance += amountToTransfer;
this.balance -= amountToTransfer;
}

这将与您的实例 firstAccount.transfer(amount, secondAccount) 一起使用,并将金额 firstAccount 转移到 第二个帐户。我建议使用这种方式,而不是使用 static 选项。

下面是一个关于如何在 main 中使用两者的示例:

public static void main(String[] args){
SavingsAccount firstAccount = new SavingsAccount("A", 5000);
SavingsAccount secondAccount = new SavingsAccount("B", 3000);

int amount = 500;
firstAccount.transfer(amount, secondAccount); //This is the non-static variation
transfer(amount, firstAccount, secondAccount); //Static variation, you might need to use the Class.transfer
}

关于java - java中如何让对象相互交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com