Accessor Methods in Java

后端 未结 8 1358
野趣味
野趣味 2021-01-03 06:44

So I have a question on \"setter\" and \"getter\" methods and how useful they are or aren\'t.

Let\'s say I just write a very basic program like the following:

<
相关标签:
8条回答
  • 2021-01-03 07:37

    The java keyword "private" in front of each of the Account class’s field declarations, prevents direct reference to that field. If you put myAccount.name = “whatever” in the UseAccount class, you get the error message: "name has private access in Account". Instead of referencing myAccount.name, the UseAccount programmer need to call method myAccount.setName or method myAccount.getName. These methods are called accessor methods, because they provide access to the Account class’s fields.

    0 讨论(0)
  • 2021-01-03 07:38

    Try this Golden Rule of Object Oriented Programming.

    1. Create private Instance variables.

    2. Create public getters and setters to access those Instance variable.

    3. This methodology is called Encapsulation. Though Encapsulation can be used in a different way, that has importance in Design Patterns, Like Those Behaviors which keeps changing must be encapsulated in an Abstract Class or Interfaces.

    4. Well now back to the topic of Getter and Setter....

    Getter and Setter helps Validating the Input to the Instance Variable.

    For eg: Assume i got a method to assign the Age of the Dog, Now the age can NoT be negative, If i dont have setter method, then i will not be able to Validate the Input of age.

    private int age;
    
    public void setDogAge(int age){ 
        if (age>0){
            this.age = age;
        } 
        else{
            System.out.println("Please Enter a Valid Age");
        }
    }
    
    0 讨论(0)
提交回复
热议问题