What is the purpose of having a private variable with the appropriate setter method?

When I have a setter method for a private variable in java, what is the purpose of making the variable private?

We have private variables to prevent the user from directly accessing the state of the instance. But sometimes we have the appropriate setter and getter methods for accessing and changing the state of a private variable. If so, why do we make the variable private? Instead, can we just have a public variable?

+5
source share
5 answers

The rationale is that you are hiding the implementation. When you call

setX(23);

your corresponding variable xis hidden from client classes and cannot be directly detected or modified.

?

  • . x , () a string, a double .., . x , setX() - , .
  • setter, .. - x (, ) .
  • ( Java, OO). Java- , JavaBeans. .. x getX()/setX() ( isX(), a boolean). , .

, , ( ). / .

+13

, : - , .

, : - , Java AtomicFloat, - , AtomicInteger - int float. :

class AtomicFloat {
     private AtomicInteger value;

     public float get() {
         // turn value into float
     }

     public void set(float newValue) {
         // turn newValue into int
     }

     // CAS and whatever else
}

, , : AtomicFloat, , . , , AtomicInteger. !

+1

- . Date (, Java Jodatime Date), , int-:

public int dayOfMonth;
public int monthOfYear;
public int year;

Date 234- 56- .

, , setter , setter , (, setMonth() 1 12 ..),

0

setter - , - , control changes to a variable.
private controls the accessiability of a variable
write-only ,

0

, , :

Class Car {
    Private int wheels
    Private int tyres
    Private time lastUpdated

    - setWheels(int i) {
        lastUpdated = Time.Now
        wheels = i
        tyres = i
    }

    - setTyres(int i) {
        lastUpdated = Time.Now
        tyres = i
        wheels = i
    }
}

, , , .

This is a simple example, so the number of wheels is directly related to the number of tires, so we can set this when you use the setter methods, and we also want to know when the car was last updated, basically it allows you to perform other tasks that depend on from changing a variable.

The reason you make the variable private is because you have to use setter methods when accessing the variable from outside the class.

Hope this helps.

Thanks, Will

0
source

All Articles