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:
