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

+1 vote
13 views
asked Nov 3 by Hitesh Garg (251 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 by Rahul Singh (328 points)  
selected Nov 4 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

41 questions

27 answers

3 comments

20 users

Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...