【问题标题】:How can I change the variable of my Object?如何更改对象的变量?
【发布时间】:2020-11-20 20:49:08
【问题描述】:

我在 Google 上搜索了很多,但这个问题让我很头疼,因为在 Discord 上没有人能帮我解决这个问题。现在我在这里寻求帮助。

这就是我用来制作对象的类

public class Main {
    public static void main(String[] args) {
        Konto mats = new Konto("Mats", 200);
        mats.getAccount();
    }
}

那就是它的类:

public class Konto extends Bankautomat{
    String name;
    int balance;

    String prefix = "[Deutsche Bank]";

    public Konto(String name, int balance){
        this.name = name;
        this.balance = balance;
        System.out.println("New Account successfully registered!");
    }

    public void getAccount(){
        System.out.printf("\n%s\nName: %s\nBalance: %d$\n", prefix, name, balance);
    }

}

现在我想创建一个 Bankautomat 类,我可以在其中从“Mats”向 Konto 存钱

public class Bankautomat {

    public void deposit(int amount){

    }
}

但我不能使用 mats.balance += amount 并且设置或获取东西也对我没有帮助 请帮忙谢谢

【问题讨论】:

  • 将余额转移到 Bankautomat 类中如何?

标签: java class object variables instance


【解决方案1】:

按照您的设置方式,Konto 现在扩展了 Bankautomat。换句话说,所有Kontos 都是Bankautomats,但反之则不然。由于您只在Konto 类中声明了balance 字段,这意味着它是Kontos 的属性,但不一定是所有Bankautomats 的属性,所以Bankautomat 对象没有这个,除非它特别Konto

为了能够在Bankautomat 中访问它,您应该将该字段移至Bankautomat 类。然后,您将能够从两者访问它,因为 KontoBankautomat 并将继承它。像这样的:

public class Konto extends Bankautomat{
    String name;

    String prefix = "[Deutsche Bank]";

    public Konto(String name, int balance){
        super(balance);  // this calls the constructor of the superclass
        this.name = name;
        System.out.println("New Account successfully registered!");
    }

    public void getAccount(){
        System.out.printf("\n%s\nName: %s\nBalance: %d$\n", this.prefix, this.name, this.balance);
    }

}

和其他类:

public class Bankautomat {
    int balance;

    public Bankautomat(int balance) {
        this.balance = balance;
    }

    public void deposit(int amount){
        ...
    }
}

【讨论】:

  • 好的,谢谢,但为什么我必须调用超类构造函数。因为我试过没有它,它也有效
猜你喜欢
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 2021-12-11
  • 2015-11-10
  • 2018-05-18
相关资源
最近更新 更多