Search code examples
javavariablesglobal-variables

Externally visible but not modifiable, but internally modifiable?


Before I get on with the question, in all my searches I cannot seem to find this, so I am sorry if it is a dupe. Now to the question:

Is there a modifier to make a variable visible but not modifiable outside of it's class without changing it's modifiable inside it's class? So basically to other classes it would be a public final but to the class it resides in it's just public. I found this and this, but neither one quite answers my question.

Again, sorry if this is a duplicate question and thanks ahead of time.


Solution

  • Is there a modifier to make a variable visible but not modifiable outside of it's class

    Make it private and expose only getter method for other classes to access. If its public then you can't stop it to make modifiable by other class. If a class can access it then it can modify it also.

    Try to avoid using public modifies for instance variables. Always access it using public getter & setter methods that give you more control.

    For e.g. in setter method you can check for the validity of the passed value.


    Class level access modifiers (java classes only)

    Only two access modifiers is allowed, public and no modifier

    • If a class is ‘public’, then it CAN be accessed from ANYWHERE.
    • If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.

    Member level access modifiers (java variables and java methods)

    All the four public, private, protected and no modifer is allowed.

    • public and no modifier – the same way as used in class level.
    • private – members CAN ONLY access.
    • protected – CAN be accessed from ‘same package’ and a subclass existing in any package can access.

    For better understanding, member level access is formulated as a table:

    enter image description here