Java Access Modifiers – The easiest way to understand

The java access modifier defines the accessibility of the class, constructor, method, or variable within the packages.
It is also applied to share the data and behaviors of the class to other classes. Including within the package, or in any other packages.

This tutorial will explain the access modifiers deeply with examples and images. Therefore, there are four types of access modifiers in java:

  • Protected
  • Public
  • Private
  • Default

As you can see, the class field that have arrows and without x symbol are visible to the other classes. Therefore, other classes can access and use that field. For the arrows that have X symbol means the field is not visible to the other classes:

Figure 1

Let’s take a look at further explanations and examples for each type of access modifier.

Protected Access Modifier

The methods or variables that have protected access modifier are only visible within the same package. Therefore, the other classes outside of the package are unable to access these variables or methods. Let’s take a look at the figure below for the class with protected access modifier:

Figure 1.1

In above, the class 1 inside of package A has a variable named field with a protected access modifier. Therefore, it is not visible in the package B. However, it can only access within the package A. In actual java code the protected access modifier declaration looks like this:

Class1.java:

package packagea;

public class Class1 {
	protected static String field = "This is the Field of class 1";
}

Refer to this post for more information about the basics and installation of Java: http://lgeratech.com/2020/01/java-core-programming-in-2020/#Install_Java

As you can see, In the code, the variable field is declared with a protected keyword at the start of the line, so now let’s try to access it in another class with the same packages.

Refer to this post for more information about static and String keyword: http://lgeratech.com/2020/01/java-core-programming-in-2020/#Java_Basic_Syntax

Class2.java:

package packagea;

public class Class2 {
	
	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

In code above, we just access the field inside of class 2 and print the value of it in the console using System.out.println(Class1.field);, after you run the code, it prints the “This is the Field of class 1”, meaning class 2 can access the protected field.

Classes with a different packages

How about in other classes with different packages, let’s take a look at the code below:

Class3.java:

package packageb;

import packagea.Class1;

public class Class3 {
	
	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

In the above code, the first thing you must do is import class 1 in class 3 since it is in the different packages like we specified in the code above which is import packages.Class1;, now let’s do the same thing like print the value of the field System.out.println(Class1.field); and once you execute the code, you will get this error message:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The field Class1.field is not visible at packageb.Class3.main(Class3.java:8)

The error means that field is not visible in class 3. Therefore, you can’t use the field with protected keyword in other classes with different packages. However, there is another thing you need to know about this access modifier. See another figure below:

Figure 1.1.1

As you can see above in figure 1.1.1, the field in class 1 are now visible in class 3, and the reason is class 3 extended the class 1 as its parent, so now class 3 is a subclass of class 1, meaning the protected variables or methods are only visible in subclasses and within the package.

let’t change the code in Class3.java, and then extend the Class1 to define it as parent class of the Class3, in the code below we added this like public class Class3 extends Class1:

package packageb;

import packagea.Class1;

public class Class3 extends Class1{

	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

Once you run the code, the “This is the Field of class 1” will be displayed.

Public Access Modifier

The methods or variables with a public access modifier can be visible to other classes either in the same package or other packages, let’s take a look at the figure below for the class with protected access modifier:

Figure 1.2

As you can see on the figure above, both class 2 and 3, can access the field even if they are in the different packages, in the actual code you can import and use this field in both classes, and have the same output without error message:

Class1.java:

package packagea;

public class Class1 {
	
	public static String field = "This is the Field of class 1";

}

To define the public access modifier, add the public keyword at the beginning of the variable, once you declared the variable as public, then try to access it in other classes and then run the code to see the result, see the Class2.java and Class3.java for the example code:

Class2.java:

package packagea;

public class Class2 {
	
	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

Class3.java:

package packageb;

import packagea.Class1;

public class Class3 {

	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

If you try to run the Class2.java and Class3.java, you will see that it has no error, meaning the variable is visible in any classes and any packages.

Default Access Modifier

The methods or variables that don’t have any access modifier are called default access modifier, this access modifier is similar to the protected access modifier, and it can only be accessed, in the classes inside of the package, and not in the other classes even if in subclasses outside of the package, let’s take a look at the figure below for the class with default access modifier:

Figure 1.3

As you can see in figure 1.3, the class 1 inside of package A has a variable named field with a default access modifier, and it is not visible in the package B, it can only access within the package A, In actual java code the default access modifier declaration looks like this:

package packagea;

public class Class1 {
	
   static String field = "This is the Field of class 1";

}

The default access modifier doesn’t have any keyword, in the code declare a variable, without any access modifier keyword like private, public, and protected.

Class2.java:

package packagea;

public class Class2 {
	
	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

Class3.java:

package packageb;

import packagea.Class1;

public class Class3 {
	
	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

In the above code, and once you execute the code in Class2, it successfully displays the field value on the console, but while executing the Class3, you will get this error message:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The field Class1.field is not visible at packageb.Class3.main(Class3.java:8)

Like I’ve mentioned to you, the default access modifier is not visible to the other classes outside of the package, and that’s why java throws exception error.

Private Access Modifier

Private access modifier is the opposite of the public access modifier, technically, the public modifier can be visible in any classes either within the package or outside of the package, but private is not visible outside of the class, which is in other classes, both inside, or outside of the package:

Figure 1.4

Let’s this in actual code again, declare the private field in class 1 same as we did on the other access modifier, then try to access the field in class 2 and class 3 to see the results:

Class1.java:

package packagea;

public class Class1 {
	
  private static String field = "This is the Field of class 1";

}

Class2.java:

package packagea;

public class Class2 {
	
	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The field Class1.field is not visible at packagea.Class2.main(Class2.java:6)

Class3.java:

package packageb;

import packagea.Class1;

public class Class3{

	public static void main(String[] args) {
		System.out.println(Class1.field);
	}
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The field Class1.field is not visible at packageb.Class3.main(Class3.java:8)

Both Class2 and Class3 throws exception error because the private access modifier field is not visible outside of the Class1.

Conclusion

The purpose of the access modifier is to control the access level of the classes, fields, methods, or constructors in any projects, it is a good practice if you figure out which are public or private fields, methods or constructor inside of the project because large projects have hundreds of java classes and its difficult to find which part of the classes are reusable and not reusable codes.
In OOP programming access level is very common, if you don’t know about OOP you can refer to this post:
See the figure below for the summary of access modifiers and the access level of each modifier:

Figure 2

10 thoughts on “Java Access Modifiers – The easiest way to understand

  • AffiliateLabz
    February 16, 2020 at 2:01 am

    Great content! Super high-quality! Keep it up! 🙂

  • Briansmilk
    April 2, 2020 at 12:09 pm

    Many thanks extremely valuable. Will share website with my buddies.

  • LarryHouth
    April 24, 2020 at 6:13 pm

    Our adept staff of bargain school writers, scientists and students make.

  • JamesSor
    April 29, 2020 at 2:54 am

    I love reading through your web site. Thank you!

  • ปั้มไลค์
    July 9, 2020 at 3:56 am

    Like!! Really appreciate you sharing this blog post.Really thank you! Keep writing.

  • Myrl Thornbury
    July 14, 2020 at 6:57 pm

    hi!,I really like your writing very much! share we keep up a correspondence extra approximately

  • Britt Rottinghous
    July 20, 2020 at 12:04 pm

    I went over this web site and I think you have a lot of great information, saved to my bookmarks (:.

  • balenciaga
    August 9, 2020 at 11:47 pm

    Good post. I be taught something more difficult on totally different blogs everyday. It would all the time be stimulating to learn content from different writers and apply just a little one thing from their store. I抎 want to use some with the content on my weblog whether you don抰 mind. Natually I抣l provide you with a link in your internet blog. Thanks for sharing.

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.

BCF Theme By aThemeArt - Proudly powered by WordPress.
BACK TO TOP