使用getter和setter函数可以考虑?

问题描述 投票:0回答:2

我正在做一个涉及创建帐户的程序,我需要创建它以便扫描特定数据以执行指定的命令。是适合它的getter和setter函数吗?

public class Account {

    //data
    private int userId;
    private String password;
    private char type;

    public Account(int userId, String password, char type) {
        this.userId = userId;
        this.password = password;
        this.type = type;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public char getType() {
        return type;
    }

    public void setType(char type) {
        this.type = type;
    }


    //methods
    public boolean verifyLogin(int usrid , String pass)
    {
      if((usrid == userId) & (pass == password)){
          return true;
      }  
      else{
        return false;
    }
}
java oop getter-setter
2个回答
2
投票

您的getter和setter看起来很适合访问此类的数据。

您需要非常小心的是如何检查密码是否正确。

在您的实现中,您使用pass == password来比较两个字符串。这是不正确的,你应该使用pass.equals(password)


1
投票

它看起来很好,但是你需要重新考虑是否需要Setters来获取某些值。在示例中,UserID将以某种方式更改不是很常见的用例。如果要保持持久性,则不需要设置器。在构造函数中设置一次。

另外,您可以查看Lombok Project和@Getter&@ Setter注释。它会将您的代码最小化为3行。

© www.soinside.com 2019 - 2024. All rights reserved.