Scroll to top

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

Variables (Instance / Static) 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 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 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;
    private int k;
    int l;
}

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

Author avatar
JBT
https://javabeginnerstutorial.com/

78 comments

  1. Kuldeep chaudhary

    Thanks Man you explained very well.

  2. SHK

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

  3. Dnyanesh Shejul

    Nice Explanations Related to Java Modifiers…Thanks To All

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

  5. Priya

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

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

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

    • 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

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