Java Tutorial Series - Access Specifiers
In this Java tutorial, we will cover Access Specifiers - Public, Private and Protected, their visibility and the scope.
Access Modifiers in Java -
There are 4 different access modifiers in Java -
- Public
- Private
- Protected
- Default (undefined)
- private - Private access modifiers can only be accessed within the same class. Even if the class is extended by different sub-class, yet it won't be able to access the access modifier having keyword 'Private'.
- protected - Can be accessed by child classes and the parent class where the variable is declared. It works in same package although. We don't need to extend the class, if an object is created of the parent class, it will still work.
- public - can be accessed from anywhere.
- Default - works in same package. It works like protected access modifier.
All in all, we don't need to keep small details, high level summary will also work -
private - only within same class
public - from anywhere
protected - same class, subclass and same package
no modifier - same package only
Access modifiers cannot be applied to classes, they are only applicable to instance variables.
Access modifiers cannot be applied to classes, they are only applicable to instance variables.
Comments
Post a Comment