Access Modifiers in Java

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

There are three access modifiers. Not including the default access modifier. The 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 in Java.

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

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 the public it can be accessed 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 subclasses defined in the same or different package only via Inheritance.

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

Private

A variable 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 subclasses defined in the same or different package.

The only difference between protected and the 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 the Same PackageYesNoYesYes
From Any Sub Class in the 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 Modifier 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 com.jbt;

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

Sub Class in same packag

package com.jbt;

class SecondClass extends FirstClass {

    void method() {
        System.out.println(i);
        System.out.println(j); // Respect the parent child relationship irrespective of package
        System.out.println(k); // Compilation Error
        System.out.println(l); // Accessible as it is in same package


        FirstClass cls = new FirstClass();
        System.out.println(cls.i);
        System.out.println(cls.j);
        System.out.println(cls.l);
        // Private variable will not be accessible here also.
        System.out.println(cls.k); // Compilation error
    }
}

Subclass in different package

package com.jbt.newpackage;


import com.jbt.FirstClass;

class SecondClass extends FirstClass {

    void method() {
        // Access through inheritance
        System.out.println(i);
        System.out.println(j); // Respect the parent child relationship irrespective of package
        System.out.println(k); // Compilation error - private variable
        System.out.println(l); // Compilation Error - not accessible as it is in diff package


        FirstClass cls = new FirstClass();
        System.out.println(cls.i); // Accessible because it is public
        System.out.println(cls.j); // Compilation error
        // Private variable will not be accessible here also.
        System.out.println(cls.k); // Compilation error
        System.out.println(cls.l); // 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 the member of that class, even when the access level of that member is public(Important).
  • Class visibility should be checked before member visibility.
  • If a superclass has public member then it will be inherited by subclasses even if it is in other packages.
  • this always refers to the currently executing object.
  • A public member can be accessed by all other class even from other packages.
  • 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 the different package.
  • Different between protected and default comes into picture only in the case of subclass outside a package.
  • Local variables can not have access modifiers.
  • Local variables can have only final non-access modifiers that can be applied.

 

<< Order of execution Non Access Modifiers in Java >>

77 Comments Access Modifiers in Java

    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.

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. Latasri

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

    Reply
  14. Prathmesh Chavan

    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.

    Reply
  15. Priya

    An access modifier restricts the access of a class, constructor, data member and method in another class. Informative blog, thanks for sharing.

    Reply
  16. pranit

    Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. Thanks again!

    Reply
  17. Julia

    Loving the tutorial so far, but I think there may be a mistake in the example code provided for direct access vs. inheritance. Since SecondClass is a subclass of FirstClass, the print statement System.out.println(j) should be accessible because it is inherited, whereas the print statement System.out.println(cls.j) should return the error because this is an example of direct access.

    Reply
    1. JBT

      Hi Julia,

      You were quite right. Example was not very clear. So i made some changes. Please take a look and let me know if u still have some question.

      Regards

      Reply

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.