gpt4 book ai didi

java - 如何通过类名调用方法

转载 作者:行者123 更新时间:2023-12-01 13:53:35 33 4
gpt4 key购买 nike

我的作业中有一行字我很难理解。

您应该提供从帐户提取和存入指定金额的方法,以及将指定金额从一个帐户转移到另一个帐户的转账方法。 可以使用类名调用传输方法。

不太明白最后一句是什么意思。这是我所拥有的;

public class CbtBank {
private double balance;
private String firstName, lastName;
private int accountNumber;

public CbtBank(String firstName, String lastName, int accountNumber, double balance) {
this.balance = balance;
this.firstName = firstName;
this.lastName = lastName;
this.accountNumber = accountNumber;
}

public void transfer(CbtBank from, CbtBank to, double amount){
to.balance += amount;
from.balance -= amount;
}
}

还有我的main.java;

public static void main(String[] args) {
CbtBank person1 = new CbtBank("can", "berk", 3123, 100.0);
CbtBank person2 = new CbtBank("can2", "berk2", 3124, 200.0);
CbtBank.transfer(person1, person2, 50.0);
}

我无法让它以这种方式工作,但我什至不确定这是否是这个意思。有什么想法吗?

最佳答案

In the doc

In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.

那么你的要求是属于类而不是实例的方法。

静态方法可以通过其名称进行访问,因此将 CbtBank#transfer 设为静态方法。

class CbtBank
{
public static void transfer(CbtBank to,CbtBank from,double value)
{
to.balance += amount;
from.balance -= amount;
}
}

关于java - 如何通过类名调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19772531/

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