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

+1 vote
148 views
asked Nov 3, 2017 by Hitesh Garg (343 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 4, 2017 by Rahul Singh (518 points)  
selected Nov 4, 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
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...