This blog will state the usage and implementation of Java’s “get” and “set” methods.
What are the “get” and “set” Methods in Java?
The “get” method is used to return the value of the private variable, and the “set” method sets/allocates the value of the private variable. These methods are a part of the “encapsulation” process in which the sensitive data is hidden from the users.
Example 1: Getting and Setting Values in Java
In this example, the “set()” and “get()” methods functionality can be utilized first to set the value of the private variable and then fetch it with the help of the user-defined functions within the class:
In the above code block:
- Firstly, define a class named “getandset”.
- Within the class, specify a private variable named “age”.
- In the next step, define a function named “setAge()” having the stated parameter to set the value. In the function definition, pass the set value to the private variable.
- Now, declare a function for fetching the set value named “getAge()”. In its definition, simply return the “set” age.
- In the “main”, create an object of the declared class via the “new” keyword and the “getandset()” constructor, respectively.
- After that, invoke the accumulated function “setAge()” by referring to the class and setting the specified value.
- Lastly, retrieve the set value by accessing the latter class function “getAge()”.
In this output, it can be observed that the set value is retrieved appropriately.
Example 2: Getting and Setting Values by Reference in Java
In this particular example, the values can be set and get by referring to the private variable:
In the above lines of code, apply the following steps:
- Likewise, define a class named “getandset” and specify the stated private variable.
- Now, define a function named “setAge()” having the parameter “age” to set the value.
- Note that the parameter and the private variable are identical, so “this” keyword can be utilized here to omit the ambiguity in differentiation.
- The “this” keyword points to the private variable and allocates it the set value after passing it as a function argument in the main.
- After that, similarly, define the function “getAge()” to return the set value.
- In the “main”, recall the discussed approaches to create a class object, set, and get the value accordingly.
In this outcome, it can be analyzed that the ambiguity between the identical values is sorted out by passing reference.
The “get” and “set” methods in Java are a part of “encapsulation” and are used to return and set the value of the private variable, respectively. These methods can be used to modify the variable simply or by passing the reference with the help of the user-defined function. This blog discussed the approaches to utilizing Java’s get and set methods.