Access Modifiers in Java

Access modifiers help you set the level of access you want for your Class, variables as well as Methods.

There are three access modifiers. Not including default access modifier . Default is an access control which will be set when one does not specify any access modifier.

Access Control:

  • Public
  • Private
  • Protected
  • Default

Access modifiers(Some or All) can be applied on Class, Variable, Methods.

Access Modifiers for Class

Classes in Java can use only public and default access modifiers.

Public

When set to public, the given Class will be accessible to all the classes available in the Java world.

Default

When set to default, the given Class will be accessible to the classes which are defined in the same package.

Java Access Modifiers Table for Class

VisibilityPublic Access ModifierDefault Access Modifier
Within Same PackageYesYes
From Outside the Same PackageYesNo

Access Modifiers for Instance & Static Variables

Variables are eligible for all of the above mentioned modifiers.

  • Default
  • Public
  • Protected
  • Private

Note*: Visibility of the Class should be checked before checking the visibility of the variable defined inside that Class. If the Class is visible then the variables defined inside that Class will be visible . If the Class is not visible then no variable will be accessible, even if it is set to public.

Default

If a variable is set to default, it will be accessible to the classes which are defined in the same package. Any method in any Class which is defined in the same package can access the variable via Inheritance or Direct access.

Public

If a variable is set to public it can be accessible from any class available in the Java world. Any Method in any Class can access the given variable via Inheritance or Direct access.

Protected

If a variable is set to protected inside a Class, it will be accessible from its sub classes defined in the same or different package only via Inheritance.

Note:The only difference between protected and default is that protected access modifiers respect class subclass relation while default does not.

Private

A variable if defined private will be accessible only from within the Class in which it is defined. Such variables are not accessible from outside the defined Class, not even in its subclass .

Java Access Modifiers Table for Variable

VisibilityPublic Access ModifierPrivate Access ModifierProtected Access ModifierDefault Access Modifier
Within Same ClassYesYesYesYes
From Any Class in Same PackageYesNoYesYes
From Any Sub Class in Same PackageYesNoYesYes
From Any Sub Class from Different PackageYesNoYes(Only By Inheritance)No
From Any Non Sub Class in Different PackageYesNoNoNo

Access Modifiers for Methods

Methods are eligible for all of the following modifiers.

Default

When a Method is set to default it will be accessible to the classes which are defined in the same package. Any Method in any Class which is defined in the same package can access the given Method via Inheritance or Direct access.

 Public

When a Method is set to public it will be accessible from any Class available in the Java world. Any Method in any Class can access the given method via Inheritance or Direct access depending on Class level access.

Protected

If a Method is set to protected inside a Class, it will be accessible from its sub classes defined in the same or different package.

 Note:* The only difference between protected and default is that protected access modifiers respect class subclass relation while default does not.

Private

A Method that is defined private will be accessible only from within the Class in which it is defined. Such Methods are not accessible from outside the defined Class, not even its subclass .

 

Java Access Modifiers Table for Method

VisibilityPublic Access ModifierPrivate Access ModifierProtected Access ModifierDefault Access Modifier
Within Same ClassYesYesYesYes
From Any Class in Same PackageYesNoYesYes
From Any Sub Class in Same PackageYesNoYesYes
From Any Sub Class from Different PackageYesNoYes(Only By Inheritance)No
From Any Non Sub Class in Different PackageYesNoNoNo

 

Access Modifier for Local Variable

No Access Modifiers can be applied to local variables. Only final can be applied to a local variable which is a Non Access Modifer .

 

Difference between Inheritance or Direct Access

Below is illustrated the difference between inheritance and direct access.

Super Class


package jbt1;

public class FirstClass {
	public int i;
	protected int j;
	private int k;

}

Sub Class


package jbt;

import jbt1.FirstClass;

class SecondClass extends FirstClass {

	void method() {
		System.out.println(i);

		/*
		 * Here you are trying to access protected variable directly. So it will
		 * not be accessible and compile will give an error.
		 */

		System.out.println(j);

		/*
		 * As k is private so it will not be accisible to subclass neither way.
		 * Neither it can be accessed via Inheritance nor direct.
		 */
		System.out.println(k); // Compilation Error
		FirstClass cls = new FirstClass();

		
                /*
		 * Here property j is accessed via Inheritance hence it will be
		 * accessible. But same variable can not be accessed if you try to
		 * access via instance because modifier used here is protected so it
		 * will be available to sub class only via inheritance.
		 */

		System.out.println(cls.j);

		// Private variable will not be accessible here also.
		System.out.println(cls.k); // Compilation error
	}
}

Cheat sheet

  • Public, Private, Protected are 3 access modifier
  • There are 4 access levels in Java. Public, Private, Protected & Default.
  • A class can have only public and default access level.
  • Methods and Instance variable (non local) can use all 4 access levels.
  • If a class is not visible to other class there is no question of accessing member of that class, even when access level of that member is public(Important).
  • Class visibility should be checked before member visibility.
  • If a super class has public member then it will be inherited by subclasses even if it is in other package.
  • this always refers to the current executing object.
  • A public member can be accessed by all other class even from other package.
  • Private members can be accessed only by the code in the same class.
  • Default members are not visible to subclasses outside package while protected members are visible to subclassed even when they are in different package.
  • Different between protected and default comes into picture only in the case of subclass outside package.
  • Local variables can not have access modifiers.
  • Local variables can have only final non access modifiers that can be applied.
Series Navigation<< Write Hello World program using EclipseNon Access Modifiers in Java >>
By | 2017-07-09T12:07:27+00:00 April 21st, 2012|Core Java|72 Comments

About the Author:

72 Comments

  1. Nilesh December 16, 2012 at 4:41 pm - Reply

    i m new learner for core Java. can u explain the access modifiers types with examples? Thanks- Nilesh

    • admin December 16, 2012 at 4:59 pm - Reply

      Hi Nilesh,
      You can check this link. Here we have provided some examples related to access modifiers. Please look at this and let us know if you need more help.
      Thanks

      • vadivel.m September 13, 2014 at 7:05 am - Reply

        please can you tell me how to protect the java code in a home appliance give the explain.

    • Naveen Rai February 27, 2013 at 7:17 am - Reply

      there are 4 types of access modifires in java.
      1.private
      2.public
      3.protected
      4.defalt
      Private-private variableis used only inside his class not outside of his class.
      Public-public variable is use inside his class and outside his class.public variable use anywhere in java world.
      Protected-protected variable use only inside subclasses.
      Default-default variable is use only in class inside package.

      • Bhargavi March 22, 2013 at 5:08 am - Reply

        i think there 12 access modifiers in java
        bt u say those are 4 only
        which one is correct
        could u plz explain those

        • admin March 22, 2013 at 5:18 am - Reply

          Hi Bhargavi,

          Could you please tell me where you get the information that there are 12 Access Modifier in Java. And what are those AM. As per my knowledge there is only 4 in Java. Give me more details so that i can help you in this regard.

          Thanks

          • swapna May 12, 2014 at 1:14 pm

            hi sir,this is swapna now iam learning java tool so this site is very useple for me.
            thak you very much sir.

          • maheah November 29, 2014 at 4:27 am

            hai sir…
            i am new to java..as per above discusion .modifiers are like
            1.public
            2.protected
            3.default
            4.private
            5.static
            6.final
            7.abstract
            8.synchronise
            9.volatile
            10.native
            11.strictfp
            ..exept top 4.. what are others..please let me know..

          • Vivekanand Gautam December 2, 2014 at 5:04 pm

            Hi Mahesh,

            Sorry for late reply.
            You are right first 4 are Access Modifier while Others are Non Access Modifiers.

            Why it is called Access Modifiers because these(Public, Private, Protected, Default) are related to Accessibilty of Class/Method/Variable. Only these can be used for accessibility feature. Others cant be used for this purpose. Hence they are known as Non Access Modifiers.

            Hope it help.

        • satheesh July 12, 2016 at 2:02 am - Reply

          only 4types

      • kitty March 23, 2015 at 1:50 pm - Reply

        not “his” , “it’s” is used….

    • Rajesh May 18, 2016 at 7:15 am - Reply

      Very good explanation..Glory to god.. God has given wonderful teacher for me.

  2. ada December 20, 2012 at 3:20 pm - Reply

    very goooooood

  3. Jayshree April 10, 2013 at 5:04 pm - Reply

    Thanks for this great info.

  4. amit April 10, 2013 at 6:36 pm - Reply

    Excellent way of teaching java to beginners. Thanks for this great website.

  5. Ankan April 23, 2013 at 7:09 am - Reply

    This is I think one of the best websites available to teach JAVA for Beginners….As well as it helps in recapitulating seasones coders too.

  6. santhiya August 26, 2013 at 6:58 am - Reply

    wow…. way of describing access modifiers is simply superb easy to understand… thanks

    • admin August 26, 2013 at 6:23 pm - Reply

      Thanks for your nice comment

      • yoogesh January 12, 2016 at 10:47 pm - Reply

        This is clearly the wrong information.
        As far as i know, the term of “Access Modifiers” is used in C++ but not in java.
        In java, there is no concept of Access modifiers. instead there is just a concept of modifiers in java and there are 12 modifiers.
        so in java, you can not say access modifiers ( the term which you used in c++)

        • J Singh January 16, 2016 at 7:06 am - Reply

          Could you please provide the list of 12 modifiers. And where you read this?

  7. Yash Agrawal October 4, 2013 at 7:07 am - Reply

    Hiii.. Admin..
    you need to be more clear with default and protected access specifier.
    for hint-
    use and access both are different thing.
    hope it will help you.

    thanks.

  8. Sweety October 18, 2013 at 9:00 am - Reply

    Hi, I would like to bring to admins notice that,In private section, just above table “Java Access Modifiers Table for Variable”, you have written protected instead of private.

    Pls make correction as soon as possible.bcos, this site is very nice, useful for many java beginners.So, If the detail provided by you is mistake -free then it will be very useful.

    Thank you.

    • Vivekanand Gautam October 19, 2013 at 4:04 pm - Reply

      Hi Swety,

      Thanks for your nice comment. I have corrected the mistake.

      In case you need more help do let me know.

      Thanks

  9. vsenky October 28, 2013 at 1:08 am - Reply

    not good bro,you should give more details.Actually there are 12 access modifiers in java.

  10. sydeesh December 1, 2013 at 2:33 pm - Reply

    Hi i’m new to java ..i’m eagerly learn java so i came to this site ,why i don’t see the topics Abstraction and encapsulation topics in this tutorials. please let me know if i’,m unable to find the topics

    Thanks,

  11. vishnu December 28, 2013 at 5:21 am - Reply

    Great explanation

  12. Jeevan January 14, 2014 at 11:21 am - Reply

    What is direct access in “Via Inheritance or Direct access”? Please share an example.

    • Vivekanand Gautam January 14, 2014 at 6:04 pm - Reply

      Hi Jeevan,

      I have updated Article. It now includes example to make you understand the difference between these two. Please check article again let me know still you have any question.

      Thanks

  13. V P KANNAN January 19, 2014 at 5:39 am - Reply

    Under the heading ‘Access Modifiers for Methods’, you have given the very same explanation as that of the ‘Access Modifiers for Variables’ without even changing the word ‘variable’ to ‘method’. Kindly rectify.

  14. Jeevan January 28, 2014 at 7:14 am - Reply

    1. What is “Access via instance”?
    2. Using “extends” with class name, as in above example with “second class” is called inheritance, correct?
    3. direct access means, when we create an object of class and call/access class’s property ?
    example:

      
    public class FirstClass {
        public int i;
        protected int j;
        private int k;
     
    }
    
    class SecondClass extends FirstClass {
         void method() {
    	FirstClass cls = new FirstClass();
         System.out.println(cls.j);
                 }
    }
    


    if Yes, then what's the difference between "direct access" and "access via instance"?
    4. I am able to access "j" but you said that it wont be accessible?

      
    public class SecondClass extends FirstClass {
    	
    	public void method1() {
    
    		System.out.println(i);
    		System.out.println(j);
    
    		FirstClass firstClass = new FirstClass();
    		System.out.println(firstClass.j);
    
    	}
    It prints value of j in console.
    


    5. do I have to create public method, cause w/o it I wasn't able to run?
    In point number 4, initally I wrote:

      
    void method1(){ 
    // To do
    }
    


    but it didn't run, but when I used "public" as a prefix , it ran successfully.

    • Vivekanand Gautam January 28, 2014 at 3:25 pm - Reply

      You understood the difference properly but you have not used the example properly. You should understand the usefulness of package declaration. In your example you have removed package declaration. That will make a big difference.

      Don’t remove the package declaration and see the difference you will understand.

      • Jeevan January 29, 2014 at 6:46 am - Reply

        Sir, please be specific, cause I dont want to learn on assumptions. I’ll be highly obliged if you can answer point wise.

        Thanks a lot.

        • Vivekanand Gautam January 29, 2014 at 4:10 pm - Reply

          Hi Jeev,

          I don’t understand what do you mean by assumption. I clearly provided the example. If you can’t use example properly then i can’t do anything. You should first understand what i want to say. There is no assumption.

          Second thing i am not getting paid for teaching any one here. I am just telling you guys so that you can understand. And i can’t make you understand everything.
          Would be great if you can talk to you senior or teacher who can help you.

          Thanks

          • Jeevan January 30, 2014 at 5:50 am

            Thanks for replying,
            But you have totally misunderstood me.

            There is no problem with examples, they are really nice. It is just that I couldn’t understand the reply that you gave on the my question (questions by that way, let me know, if they are too many to ask in one go).
            1. You said that “You understood the difference properly but you have not used the example properly.”, but I posted 5, which one you’re referring to, should I assume that my understanding to all 5 are correct, or you’re referring to particular point.
            2. “You should understand the usefulness of package declaration. In your example you have removed package declaration. That will make a big difference”.
            a) I have not removed any package, I have mocked the examples the way you posted above.
            b) Tutorial doesn’t talk about package, could you please show it in a example
            3. Other queries still stands as is, they are not answered?
            If you still want to answer kindly answer, otherwise it is upto you, if not teachers or seniors, there are plenty of other resources. This is sad that whatever you do, only do because you’ll get paid and if not then this statement “I am just telling you guys so that you can understand” why do you really care we understand or not, may be you just want attention on web, huh !!

          • Vivekanand Gautam January 31, 2014 at 3:47 am

            Thanks

    • Paras September 4, 2016 at 10:18 pm - Reply

      You are right jeevan
      package jbt;

      import jbt1.FirstClass;

      class SecondClass extends FirstClass {

      void method() {
      System.out.println(i);

      /*
      * Here you are trying to access protected variable directly. So it will
      * not be accessible and compile will give an error.
      */

      System.out.println(j);

      how is it access directly?(class SecondClass extends FirstClass )if you extends the class so no compiler error will occur.
      check it admin again

  15. npk March 27, 2014 at 6:29 am - Reply

    THANKS for clear picture

  16. Prince July 18, 2014 at 7:11 am - Reply

    Thanks sir.. Very good… one of the best in JAVA…

  17. PUJA1105 July 22, 2014 at 8:59 pm - Reply

    Thank U Sir . Simple and healpfull

  18. PUJA1105 July 22, 2014 at 9:01 pm - Reply

    helpful*

  19. mousumi saha August 8, 2014 at 11:09 am - Reply

    i am a beginer of java,i have one question…suppose i hava a class whic ic not public and in that class one of my variable is public,now as u told that we can use that public variable anwhere in java world so now i want to use it in an another java class but in an another file(opening another notepad) and for this i have seen that i have to extends the previous class.my question is why???everytime extends is compulsary???

  20. aditya August 19, 2014 at 7:01 am - Reply

    sir,
    i must inform you that the way you have described about these concepts is really incredible i completely appreciate the teaching method you have used over here.
    i was in a doldrum for the last five months about this topic but when i read this statement it cleared everything to me ………………
    i wish and hope you will continue to help us in the future also ……..

  21. Rajkrishna Sankhla September 20, 2014 at 5:27 pm - Reply

    Loved this site to begin with Java, Thank you so much !!

  22. sekhar December 1, 2014 at 9:23 am - Reply

    hi
    its very good meterial and also u add one more concept for constructors also.

  23. Balan January 14, 2015 at 1:54 pm - Reply

    Protected variable has been explained as: “If a variable is set to protected inside a class, it will be accessible from its sub classes defined in the same or different package only via Inheritance” By this , I get the impression that protected variables will be accessible only through sub classes. Whereas, the table of variable following this explanation says, Protected variables can be accessed within the class, other classes within the package as well as subclasses.. Which is correct ?

    • Vivekanand Gautam January 24, 2015 at 6:16 am - Reply

      Hi Balan,

      Default and Protected access modifiers are same. Except on one point. Both will be accessible in Package only.
      But Protected AM respect the parent child relationship. It means protected can be accessed outside package also but only via inheritance.

      In leh man term i would say.

      Protected AM = Default AM + Child Parent relationship

      Hope it helps.

      Regards
      Vivekanand Gautam

  24. Balan January 14, 2015 at 2:02 pm - Reply

    The method table also gives the same impression.

  25. pop April 12, 2015 at 1:51 pm - Reply

    good

  26. Nagalekshmi April 20, 2015 at 9:57 am - Reply

    All I understood from this material is if it is public : you can access it from any package same or diff,using two methods,direct access or instance basis.
    But when it comes to
    protected : you can have direct access in sub class of any pack.
    Private : no way to access outside the class.

  27. Justin George June 26, 2015 at 5:01 am - Reply

    Well defined one…

  28. Neharika July 3, 2015 at 6:46 am - Reply

    Thank You. Access Modifiers concept is well explained and easily understandable.

    Neharika

  29. sanjay July 14, 2015 at 6:35 am - Reply

    Awesome tutorial for java beginner ..good work

  30. Ankur November 19, 2015 at 10:12 am - Reply

    Hi admin
    There’s one error above i believe for protected specifier.

    /*
    * Here property j is accessed via Inheritance hence it will be
    * accessible. But same variable can not be accessed if you try to
    * access via instance because modifier used here is protected so it
    * will be available to sub class only via inheritance.
    */

    System.out.println(j);

    /*
    * Here you are trying to access protected variable directly. So it will
    * not be accessible and compile will give an error.
    */
    System.out.println(cls.j);

    I think both comments are interchanged.Please correct me if I am wrong ?

    • J Singh December 18, 2015 at 6:18 pm - Reply

      Hi Ankur,

      You are right. Problem is resolved now. And comments are interchanged.
      Thanks for pointing this error.

      Regards

  31. sneha January 17, 2016 at 5:37 am - Reply

    I think it is an appropriate example for various access protection levels for packages.

  32. BHAVIK February 20, 2016 at 3:59 am - Reply

    i m new learner for core Java. can u explain the access modifiers types with examples? Thanks- BHAVIK

  33. Sowji March 15, 2016 at 12:19 pm - Reply

    Hi, the explanation was great but can you tell me what are the valid combination of modifiers used for all classes,methods and data members.

  34. Rajesh May 18, 2016 at 7:16 am - Reply

    Very nice explanation ..God has given wonderful teacher for us..Glory to god.

  35. Nasir Ahmed U May 25, 2016 at 9:09 am - Reply

    Nice tutorial for java developers man….

  36. Latasri June 2, 2016 at 10:59 am - Reply

    can you compare modifiers and outer class, inner class,interface,method,constructor,blocks,variable in tableform

  37. Ajitha S August 25, 2016 at 10:53 am - Reply

    Can you please explain me about super() and this() methods?

  38. Tu Tran September 18, 2016 at 2:53 pm - Reply

    Actually, the below statement also caused compilation error:
    System.out.println(cls.j);

  39. NASSY December 2, 2016 at 10:22 am - Reply

    Hi,
    May I know what are the access modifiers allowed while creating data members, methods and class of inheritance.

    • J Singh January 8, 2017 at 9:04 pm - Reply

      I think i have explained it in article. If you have any specific question please let me know.

  40. Shoaib December 9, 2016 at 5:12 am - Reply

    Sir what is non subclass in different package?

    • J Singh December 25, 2016 at 6:36 pm - Reply

      It means all classes in different package and are not subclass of given class.

  41. Kuldeep chaudhary February 24, 2017 at 12:31 pm - Reply

    Thanks Man you explained very well.

  42. SHK March 10, 2017 at 12:24 pm - Reply

    this site is useful for me
    thk for very much to explain modifier

  43. Dnyanesh Shejul August 3, 2017 at 12:24 pm - Reply

    Nice Explanations Related to Java Modifiers…Thanks To All

  44. Prathmesh Chavan August 21, 2017 at 3:32 pm - Reply

    great…i’m a fresher learning core java concept, i have been referred many website to understand this specific concept of access modifiers ,but not able to clear understanding after reading this article got a clear idea and basic differences ..thank you
    will use this website further to learn all java concept.

Leave A Comment