Access Modifiers in Java

Access modifiers (AM) in java help you set the level of access you want for your class, constructor, variables as well as methods. Access levels (Access Control) can be changed by using different access modifiers.

There are three access modifiers but four access control. Default is the access control which will be set when one does not specify any access modifier.

Access Control

  • Public:        Visible to Everyone
  • Private:      Class Level Visibility
  • Protected:  Package and subclass level visibility
  • Default:      Package level Visibility

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

In below table we talk about the applicability of access modifiers for Class / Constructor / Variable / Methods.

          ApplicabilityPublic AM Private AM Protected AM Default AM
ClassYesNoNoYes
ConstructorYesYesYesYes
Variable (Static / Instance)YesYesYesYes
MethodYesYesYesYes
Local VariableNoNoNoNo

Below table talks about the visibility of access modifiers.

          VisibilityPublic AM Private AM Protected AMDefault AM
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

Class Access Modifier

Classes in java can use only public and default access modifiers. Always remember, class visibility takes precedence over member visibility. Meaning even if member is using public access modifier but class is default. Variable will not be accessible from outside package.

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.

Variable Access Modifier

Instance Variables or Static variables are eligible for all four access modifiers.

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 defined in the class in 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. (Detail about this can be found below)

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.

Method Access Modifier

Methods are eligible for all four 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 as 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 in its subclass.

Local Variable Access Modifier

No Access Modifier can be applied to local variables. Only the final Non Access Modifer can be applied to a local variable.

Constructor Access Modifier

Rules for constructors in java are the same as Methods. This means all modifiers will be applicable to constructors, even private.

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;
  int l;
  private int k;
}

Sub Class in the same package

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

A subclass in a 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

    }
}

Cheatsheet

  • Public, Private, Protected are three access modifier
  • There are four access levels in Java. Public, Private, Protected & Default.
  • A class can have only public and default access level.
  • Methods and Instance variables (non-local) can use all 4 access levels.
  • If a class is not visible to other classes, 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 a public member, then it will be inherited by subclasses even if it is in other packages.
  • this always refers to the currently executing object.
  • All classes can access public members, 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 the package.
  • Protected members are visible to subclassed even when they are in different packages.
  • Different between protected and default comes into the 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.

78 Comments

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

    • 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

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

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

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

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

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

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

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

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

    • 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

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

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

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

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

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

        • 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

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

    • 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

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

    • 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

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

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

    • Hi Swety,

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

      In case you need more help do let me know.

      Thanks

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

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

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

    • 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

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

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

        • 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

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

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

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

Leave a Reply

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.