Access modifiers in Java

UPDATED: 08 November 2019
Access modifiers in Java define the scope of class, constructor, methods and variable.

Why access modifiers?
The whole concept of access modifier is "What you want to expose from class".

There are total four access modifier public, protected, default and private in Java.

public - As name suggest any class, constructor, method and variable marked as public can be accessed within class, from sub/child-class, within same package or out of package. In other word "Can be accessed globally".

protected - Any Inner class, constructor, method and variable marked as protected can be accessed within class, from sub/child-class created in same package or different package, via object creation in same package.

You can not access protected Inner class, constructor, method and variable via object created in different package.

default - No access specifier defined for any Inner class, constructor, method and variable considered as default access level. It can be accessed within class, from sub/child-class created in same package only.

Default class, inner class, constructor, method and variables are not visible out side of package.

private - As name suggest any Inner class, constructor, method and variable marked as private can be accessed within same class only.


All access modifier's scope is given in following table.

Access Modifier same class same package
via sub-class/object
sub class in
different package
outside
the package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

0 comments :