In Java, what is the difference between default, public, protected, and private?

+1 vote
764 views
asked Nov 2, 2017 by Hitesh Garg (799 points)  

What are all the access specifiers and their restrictions in Java?
What are the rules on when to use which access specifier?

1 Answer

+1 vote
answered Nov 3, 2017 by Rahul Singh (682 points)  
selected Nov 3, 2017 by Hitesh Garg
 
Best answer

As per the official tutorial below is the sorted list of access modifiers in which we accessibility increases from left to right..

private < default < protected < public

Table of access of different access modifiers at different levels-

            | Class | Package | Subclass | Subclass | World
            |       |         |(same pkg)|(diff pkg)| 
————————————+———————+—————————+——————————+——————————+————————
public      |   *   |    *    |    *     |     *    |   *     
————————————+———————+—————————+——————————+——————————+————————
protected   |   *   |    *    |    *     |     *    |         
————————————+———————+—————————+——————————+——————————+————————
no modifier |   *   |    *    |    *     |          |    
————————————+———————+—————————+——————————+——————————+————————
private     |   *   |         |          |          |    

* : accessible
blank : not accessible
...