我如何使用字段内部方法?

时间:2017-01-02 21:35:06

标签: java

首先,这是我在这里的第一个问题。

我想在传输方法中使用双 mebleg ,我在构造函数中将 mebleg 等同于 balance ,但不幸的是,余额参数的数量不会与mebleg一起进入转移方法。我该如何解决这个问题?

我是编程新手。这就是为什么如果我的问题得到回答,你能否提出答案链接?

class Acount {

    static double mebleg;

    public static void main(String[] args) {
        Acount a = new Acount(100);
        Acount b = new Acount(0.0);
        Acount c = new Acount(0.0);
        Acount.transfer(a, b, 50);
        Acount.transfer(b, c, 25);

    }

    public Acount(double balance) {
        mebleg = balance;
    }

    public static void transfer(Acount from, Acount to, double howMuch) {
        System.out.println(Acount.mebleg - howMuch);

    }

}

1 个答案:

答案 0 :(得分:3)

如果要将该字段用于实例,则不应将该字段设为静态。如果您更改了此内容,则transfer()方法应使用from.mebleg(或关联的获取者)。

double mebleg;

public Account(double initialBalance) { mebleg = initialBalance; }

public static void transfer(Acount from, Acount to, double howMuch)
{
    from.mebleg -= howMuch;
    to.mebleg += howMuch;
}

(不讨论各种现有问题,如交易,并发,错误处理和货币单位的双倍使用)。