What is the purpose of accessors?

后端 未结 6 774
萌比男神i
萌比男神i 2021-02-13 02:09

Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.

6条回答
  •  醉梦人生
    2021-02-13 03:07

    Get and set are used in properties. They can each be public, protected, or private. Similar to accessor and mutator methods, they allow some computation when code tries to access/mutate the property. Of course, as long as you define one of get/set, the other is optional.

    Example without properties:

    private int test;
    
    public int getTest() {
        // some computation on test here, maybe?
        return test;
    }
    
    private void setTest(int test) {
        // some error/range checking, maybe?
        this.test = test;
    }
    

    With properties:

    private int test;
    public int Test {
        get {
            // some computation on test here, maybe?
            return test;
        }
        private set {
            // some error/range checking, maybe?
            test = value;   // value is a keyword here
        }
    }
    

提交回复
热议问题