Java Access Modifiers

Filed Under: Java

Java access modifiers are used to provide access control in java. Java provides access control through three keywords – private, protected and public. We are not required to use these access modifiers always, so we have another one namely “default access“, “package-private” or “no modifier“.

Java Access Modifiers

java access modifiers, protected, private, public

We can use java access modifiers with Classes as well as Class variables and methods.

We are allowed to use only “public” or “default” access modifiers with java classes.

  1. If a class is “public” then we can access it from anywhere, i.e from any other class located in any other packages etc.
  2. We can have only one “public” class in a source file and file name should be same as the public class name.
  3. If the class has “default access” then it can be accessed only from other classes in the same package.

Java Access Modifiers with Class Member

We can have all the four access modifiers for class member variables and methods. However member access modifier rules get applied after the class level access rules. For example, if class is having default access then it will not be visible in other packages and hence methods and variables of the class will also be not visible.

We will look into each of them separately and then we will show the java access modifiers usage with simple program.

Java Access Modifiers – public keyword

If class member is “public” then it can be accessed from anywhere. The member variable or method is accessed globally. This is simplest way to provide access to class members, however we should take care in using this keyword with class variables otherwise anybody can change the values. Usually class variables are kept as private and getter-setter methods are provided to work with them.

Java Access Modifiers – private keyword

If class member is “private” then it will be accessible only inside the same class. This is the most restricted access and the class member will not be visible to the outer world. Usually we keep class variables as private and methods that are intended to be used only inside the class as private.

Java Access Modifiers – protected keyword

If class member is “protected” then it will be accessible only to the classes in the same package and to the subclasses. This modifier is less restricted from private but more restricted from public access. Usually we use this keyword to make sure the class variables are accessible only to the subclasses.

Java Access Modifiers – default access

If class member doesn’t have any access modifier specified, then it’s treated with default access. The access rules are similar as classes and the class member with default access will be accessible to the classes in the same package only. This access is more restricted than public and protected but less restricted than private.

(Least Accessible) private < default < protected < public (Most Accessible)

Below table summarise above access modifiers with respect to different classes in the same package or other package and subclasses.

java access modifiers

Let’s write some simple classes where we will see the java access modifiers in action.

TestA.java


package com.journaldev.access;

class TestA {

	public static void methodPublic(){
		methodPrivate();
	}
	
	protected static void methodProtected(){
		methodPrivate();
	}
	
	static void methodDefault(){
		methodPrivate();
	}
	
	private static void methodPrivate(){}
}

Note that TestA class has default access and the private class method is accessible to all other parts of the same class.

TestB.java


package com.journaldev.access;

import com.journaldev.access.TestA;

public class TestB {

	public static void main(String args[]){
		TestA.methodPublic();
		TestA.methodProtected();
		TestA.methodDefault();
		
	}
	
	public static void methodPublic(){
		
	}
	
	protected static void methodProtected(){
		
	}
	
	static void methodDefault(){
		
	}
	
	private static void methodPrivate(){}

	
}

Note that TestB is in the same package as TestA class and hence it is able to access it’s class members. private members are not accessible but all other members are accessible because of the same package.

TestC.java


package com.journaldev.access.child;

import com.journaldev.access.TestB;

public class TestC {

	public static void main(String[] args) {
		TestB.methodPublic();
	}

}

TestB class is accessible because it’s public. Only public members of TestB class is accessible because TestC class is not in the same package nor it’s subclass of TestB.

TestE.java


package com.journaldev.util;

import com.journaldev.access.TestB;

public class TestE extends TestB {

	public static void main(String[] args) {
		TestB.methodPublic();
		TestB.methodProtected();
	}

}

Since TestE class is subclass of TestB, we can access TestB protected members.

Thats all for the java access modifiers, it’s simple to understand. Just don’t confuse with default and protected access.

Easy way to remember is that default access is more restricted than protected and protected members are accessible in subclasses.

Recently I made a video to explain java access modifiers in detail, you can watch it below on YouTube.

Comments

  1. Pragun says:

    In TestE.java, what if we had tried to acess members of Test A? Would we have got the error at the import statement itself because of the fact that TestA sits in another package.

  2. Pradeep says:

    Hi pankaj,

    Is there any article do you have to learn access modifiers in deep.

  3. Nurhidayat says:

    Hi! Can I share the access modifier table image? (just the image)

    1. Pankaj says:

      Sure, go ahead. An attribution would be nice though. 🙂

    2. shiridi says:

      sir,
      why we can’t provide protected access to class in package,please tell me the reasons for why can’t create protected class in package

  4. Ahmad Sayeed says:

    I am confused about the image you have shown here.

    Mentioning the image link: https://www.journaldev.com/wp-content/uploads/2013/10/java-access-modifiers-table-1.png

    If other package class can’t access protected things then how other package sub-classes can access protected things.

    1. Pankaj says:

      I don’t understand what is the confusion you have. Let’s say you have class A and in another package you have two classes – B and C. Class B is inherited from A. So B will have access to protected properties of A but C won’t have. I hope it’s clear now.

      1. Ahmad Sayeed says:

        Yes now I got it. I was mising the “is a relationship”. Is it also work same in case of “has a relationship”.

        1. Ahmad Sayeed says:

          Of course it does not work same in case of has a relationship… Thank for sharing.

  5. radhika says:

    well explained!

  6. mayur says:

    Informative and insightful article!
    As java beginner i have been looking for this ‘ Java access modifiers’ concept in detail and here i have found it well explained and understanding with examples. Thanks a lot for sharing this, will be looking forward to read more from you!

  7. Shashibhushan Singh says:

    Hi Nitish,
    you says about access modifier about default access level its correct only if you will try to access default method from subclass of same package it will be accessible but outside the package you can’t .

  8. Nitish says:

    Hi,
    There seems a mistake in access modifier image content. Details about protected and default access modifier is wrong. Please refer to http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html for more details.

  9. PRAVEEN KUMAR BADAM says:

    “We can have only one “public” class in a source file and file name should be same as the public class name”

    Can you please elaborate it.. if we don’t do this, will get a compilation error..why this restriction is imposed??

    1. Aliasger Motiwala says:

      When you have a public class in a file your file name should be the public class name.
      But if there are no public class then you can name your file whatever you want and run the program with the class name having the main method

      We can have only one “public” class in a source file
      According to me it is Java Bean norms sort of a contract

  10. Buddhi Bal Thapa says:

    Thank you for this great post. I’m still confused on this. What is the default access modifier of class and methods when creating the class and method for the first time?

  11. Krishna says:

    Hi Pankaj Sir,Thanks a LOT for this Post.Beginners like me will get more Knowledge from your articles since you explain them in simple terms.One More Request.In the concepts that you explain,Please include more examples as we can understand the concepts easily if they are explained with easy,simple examples.Thanks.~Krishna.

    1. Pankaj says:

      Most of the times I try to explain things with simple examples and then proceed to rather tough ones to clarify all different kinds of doubts you might face while working with java.

      1. Madiraju Krishna Chaitanya says:

        Hi Pankaj Sir,
        Thank You for the consideration.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages