Access Modifiers in Java

This entry is part 11 of 34 in the series Core Java Course

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

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

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

Visibility Public Access Modifier Private Access Modifier Protected Access Modifier Default Access Modifier
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(Only By Inheritance) No
From Any Non Sub Class in Different Package Yes No No No

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

Visibility Public Access Modifier Private Access Modifier Protected Access Modifier Default Access Modifier
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(Only By Inheritance) No
From Any Non Sub Class in Different Package Yes No No No

 

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

Sub Class

Series Navigation<< Write Hello World program using EclipseNon Access Modifiers in Java >>

70 Comments Access Modifiers in Java

  1. Pingback: Java Variables Tutorial for Beginners | Java Beginners Tutorial

  2. Nilesh

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

    Reply
    1. admin

      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

      Reply
    2. Naveen Rai

      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.

      Reply
      1. Bhargavi

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

        Reply
        1. admin

          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

          Reply
          1. swapna

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

          2. maheah

            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..

          3. Vivekanand Gautam

            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.

  3. Pingback: Java Beginners Tutorial Java Class Tutorial | create java class tutorial | create class object tutorial

  4. Ankan

    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.

    Reply
      1. yoogesh

        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++)

        Reply
  5. Yash Agrawal

    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.

    Reply
  6. Sweety

    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.

    Reply
    1. Vivekanand Gautam

      Hi Swety,

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

      In case you need more help do let me know.

      Thanks

      Reply
  7. sydeesh

    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,

    Reply
    1. Vivekanand Gautam

      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

      Reply
  8. V P KANNAN

    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.

    Reply
  9. Jeevan

    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.

    Reply
    1. Vivekanand Gautam

      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.

      Reply
      1. Jeevan

        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.

        Reply
        1. Vivekanand Gautam

          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

          Reply
          1. Jeevan

            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 !!

    2. Paras

      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

      Reply
  10. mousumi saha

    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???

    Reply
  11. aditya

    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 ……..

    Reply
  12. Balan

    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 ?

    Reply
    1. Vivekanand Gautam

      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

      Reply
  13. Nagalekshmi

    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.

    Reply
  14. Ankur

    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 ?

    Reply
  15. BHAVIK

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

    Reply
  16. Sowji

    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.

    Reply
  17. Latasri

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

    Reply
  18. NASSY

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

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *