Java Access modifiers & getters setters in Java
Access Modifiers specify where a property/method is accessible. There are four types of access modifiers in java :
You can see that the above code produces an error that we're trying to access a private variable outside the class. So, is there any way by which we can access the private access modifiers outside the class? The answer is Yes! We can access the private access modifiers outside the class with the help of getters and setters.
Getters and Setters :
In the below code, we've created total 4 methods:
1. setName(): The argument passed to this method is assigned to the private variable name.
2. getName(): The method returns the value set by the setName() method.
3. setId(): The integer argument passed to this method is assigned to the private variable id.
4. getId): This method returns the value set by the setId() method.
As you can see that we've got our expected output. So, that's how we use the getters and setters method to get and set the values of private access modifiers outside the class.