Concept

How do accessor and mutator methods use this to access instance variables?

ComputerScienceOne / Accessor & Mutator Methods

"Since we have made all the member variables private, no code outside the class may access or modify their values. It is generally good practice to make member variables private to restrict access. However, if we still want code outside the object to access or mutate (that is, change) an instance’s variables, we can define accessor and mutator methods (or just simply getter and setter methods) to facilitate this. Each getter method returns the value of the instance’s variable while each setter method takes a value and sets the instance’s variable to the new value. It is common to name each getter/setter by prefixing a get and set to the variable’s name using lower camel casing.\n\nFor example:\n\n1 public String getFirstName() {\n\n2 return firstName;\n\n3 }\n\n4\n\n5 public void setFirstName(String firstName) {\n\n6 firstName = firstName;\n\n7 }\n\nIn the setter example, there is a problem: the code has no effect. There are two variables named firstName: the instance’s member variable and the variable in the method parameter. The scoping rules of Java mean that the parameter variable name(s) take precedent. This code has no effect because it is setting the parameter variable to itself. It is essentially doing the following.\n\n1 int a = 10;\n\n2 a = a;\n\nTo solve this, we use something called open recursion. When an instance of a class is created, for example, Student s = ...; the reference variable s is how we can refer to it. This variable, however, exists outside the class. Inside the class, we need a way to refer to the instance itself. In Java we use the keyword this to refer to the instance inside the class. For example, the member variables of an instance can be accessed using the this keyword along with the dot operator. In our example, this.firstName would refer to the instance’s firstName and not to the parameter variable. Even when it is not necessary to use the this keyword (as in the getter example above) it is still best practice to do so.\n\nOur updated getters and setter methods would thus look like the following.\n\n1 public String getFirstName() {\n\n2 return this.firstName;\n\n3 }\n\n4\n\n5 public void setFirstName(String firstName) {\n\n6 this.firstName = firstName;\n\n7 }"

Related Ideas

How do accessor and mutator methods use this to access instance variables? | ComputerScienceOne | Bifalgorithm | Bifalgorithm