Normally you do not have to make your Instance/ class variables public because you have a gentleman's agreement with OOPs that you will implement Abstraction and Encapsulation. Instead you provide public set and get methods to manipulate the variable. This lets you change the way the variables are stored, or add extra validation checks.
The lurnQ will show us how to work with set and get methods.
In this lurnQ, we will continue to explore getters and setters. As explained above, these methods give us access to our private class variables. Other methods need to access the instance variables in your class. But because you have declared them as private, it means they are only accessible within that class. To access them from outside that class, you have to use set and get methods. Any other program that creates instances of a class will use these methods to access your data members. Note that a member does not need a set method when its value is changed in other methods.
We will have to see this lurnQ so as to master how to use set and get methods.
Get and set method refer to getting and setting these values:Why? Because these instance variables are private.
- //private variable
- private String employeeID; //ID for the employee
- private String employeeName; //Name of the employee
- private int hourlyRate; //the amount in dollars
The get methods (accessor methods) return the value of the member they are associated with.Set methods set values for data members.
We also need to know that get/set methods are not compulsory but we include them for data members when other classes require access to them.
Lets see how to create get and set methods here...