#2 Java Access Modifiers


       Access Modifier is one which control level of access you wants to apply on your class, methods, constructors and variables. Some or All access modifier can be applied to Class, Methods, Constructors  and  Variables.

There are 3 types of Access modifiers: Public, Private and Protected. 
There are 4 types of Access levels: Public, Private, Protected and Default.

1) Class Access Modifiers: There are two access modifiers applicable to class.
        a) Public: Such class can be accessible by any class.
        b) Default: Such class can only be accessible by class within same package.

Visibility Public Default
Within Same Package Yes Yes
From Outside the Same Package Yes No


2) Variable Access Modifiers: There are four access modifiers applicable to variable.
        a) Public: Such variable can be accessible by any class through inheritance or direct access.
        b) Private: Such variable can only be accessible by class which defines it.
        c) Protected: Such variable can be accessible by any class in same package or any sub class of its defined class through inheritance.
        d) Default: Such variable can be accessible by any class in same package.

Visibility Public Private Protected Default
Within Same Class Yes Yes Yes Yes
From Any Class in Same Package Yes No Yes Yes
From Any Sub Class in Same Package Yes No Yes Yes
From Any Sub Class from Different Package Yes No Yes (through Inheritance) No
From Any Non Sub Class in Different Package Yes No No No


3) Method Access Modifiers: There are four access modifiers applicable to method.
        a) Public: Such method can be accessible by any class through inheritance or direct access.
        b) Private: Such method can only be accessible by class which defines it.
        c) Protected: Such method can be accessible by any class in same package or any sub class of its defined class through inheritance.
        d) Default: Such method can be accessible by any class in same package.

Visibility Public Private Protected Default
Within Same Class Yes Yes Yes Yes
From Any Class in Same Package Yes No Yes Yes
From Any Sub Class in Same Package Yes No Yes Yes
From Any Sub Class from Different Package Yes No Yes (through Inheritance) No
From Any Non Sub Class in Different Package Yes No No No