3. Modifiers
1. Modifiers are Java keywords that provide information to compiler about the nature of the code, data and classes.
2. Access modifiers - public, protected, private
- Only applied to class level variables. Method variables are visible only inside the method.
- Can be applied to class itself (only to inner classes declared at class level, no such thing as protected or private top level class)
- Can be applied to methods and constructors
- If a class is accessible, it doesn't mean, the members are also accessible. Member's accessibility determines what is accessible and what is not. But if the class is not accessible, the members are not accessible, even though they are declared public.
- If no access modifier is specified, then the accessibility is default package visibility. All classes in the same package can access the feature. It's called as friendly access. But friendly is not a Java keyword. Same directory is same package in Java's consideration.
- 'private' means only the class can access it, not even sub-classes. So, it'll cause access denial to a sub-class's own variable/method.
- These modifiers dictate, which classes can access the features. An instance of a class can access the private features of another instance of the same class.
- 'protected' means all classes in the same package (like default) and sub-classes in any package can access the features. But a subclass in another package can access the protected members in the super-class via only the references of subclass or its subclasses. A subclass in the same package doesn't have this restriction. This ensures that classes from other packages are accessing only the members that are part of their inheritance hierarchy.
- Methods cannot be overridden to be more private. Only the direction shown in following figure is permitted from parent classes to sub-classes.