需要帮助使用setter和getter

时间:2015-02-16 18:46:39

标签: java getter-setter

我对安装者和吸气者都很陌生。我正在研究一个简单的程序,试图更好地使用它们。我有两个课程,我想要做的就是为一个随机的人做一个帐户,设定一个平衡并退出它。我不认为我正确地使用了安装者和吸气剂,如果有人可以引导我正确的方向我会非常感激。

package SetterGettersPractice;

public class account {
private String name;
public double balance =0;
public double withdraw;
public double deposit;
public double getDeposit() {
    return deposit;
}

public void setDeposit(double deposit) {
    this.deposit = deposit;
}

public account(String name, double d){

    this.name = name;
    this.balance = d;
}

private double sumDeposits(){
    balance = balance + deposit;
    return balance;
}
private double sumWithdrawals(){
    balance = balance - withdraw;
    return balance;
}
public double getwithdraw() {
    return withdraw;
}

public void setwithdraw(double withdraw) {
    this.withdraw = withdraw;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public double getBalance() {
    return balance;
}
public void setBalance(double balance) {
    this.balance = balance;
}
public String toString(){

    return "Name="+name+" balance="+balance;
}

}

这是我的另一个班级

package SettersGettersPractice;

public class testAccount {

public static void test1(){

    account a = new account("John Doe", 100);
    a.withdraw(10.0);
    System.out.print("Balance %d", balance);
}
}

正如你所看到的,一旦我弄清楚自己在做什么,我打算尝试扩展程序。任何帮助淘汰赛的建议都会很棒!

3 个答案:

答案 0 :(得分:0)

将数据成员设为私有,您就可以了。此外,您可能希望更好地使代码格式化 - 约定说类名应该大写:Account vs account

不应设置methid setwithdraw。它包含更高级的逻辑,所以我宁愿称之为withdraw

答案 1 :(得分:0)

您的类在测试方法中也没有任何名为withdraw的方法,没有变量名称balance

我会调用我在课堂上定义的方法来正确设置和获取如下的值

package SettersGettersPractice;

public class testAccount {

public static void test1(){

    account a = new account("John Doe", 100);
    a.setwithdraw(10.0);
    System.out.print("Balance %d", a.sumWithdrawals());
}
}

虽然上面的代码可以给我预期的输出,但我会考虑将我的类重命名为Account(命名约定),我也会将setwithdraw重命名为withdraw而将sumWithdrawals重命名为{{1}基于它们中实现的功能。我建议您阅读Basics of java,其中包括命名约定,代码约定等,然后开始编码。

答案 2 :(得分:0)

如果您想使用getter和setter,那么您的代码应该更喜欢这样:

 account a = new account("John Doe", 100);
    a.setBalance(10.0);

    System.out.print(a.getBalance);

简单如下:)

P.S。班级姓名始终以大写字母开头!