Protect int only visible to specified methods

Is there a way to i

not be visible to other methods within the same class?

private int i;

private void updateI(int i) {
  this.i = i;
}

      

+3


source to share


5 answers


No - all members of the class are visible to each other.



If you find that some members of your class do not need to access a specific member, this may indicate that you should be splitting your class - think about if you can split the information more accurately, basically. This is not always a solution, of course, but of course if you find that there are two or three fields that are related to each other and that only some of the methods need to be touched, which often indicates that you should put them in your own a type.

+5


source


No, there is no such access modifier. The class is the best scope for every instance.

You might want to consider splitting the class state into a separate class so that it i

might be a field of a smaller class.



Example:

class PositiveInt {
    int i;
    public void updateI(int i) {
        if (i < 0) throw new IllegalArgumentException(...);
        this.i = i;
    }
    // ...
}

class YourClass {

    // No need to worry about 'i' staying positive in a large and complex class
    PositiveInt i = new PositiveInt();

    void updateI(int newI) {
        i.updateI(newI);
    }
}

      

+1


source


No ... private fields are only visible inside your class in all ways. You can inherit from this class to hide fields.

+1


source


Since it i

is a member variable of the class, it will be visible to other non-stationary methods. If you want its scope to be limited by a method, it cannot be a member of the class.

For a simple introduction to the scope of variables in Java, you can take a look at this page .

0


source


Why do you want the class variable to show only for a specific method.

Just declare a variable inside a method so that it is only visible to that method:

    private void updateI(int x) { 
      int i = x;
     }

      

0


source







All Articles