Categories
java

Access Modifiers in Java | The Easy Guide

This guide will help you learn the use of access modifiers in Java.

There are four access modifiers in Java.

Java access modifiers are one of the most fundamental topics in Java.

Every Java programmer must learn the use of access modifiers in Java and their unique features.

To make your learning much easier, I have added small-simple examples.

So, as always, with no further delay, let’s jump right into the topic.

Note: Before getting into this guide, first, you must learn about the concept of packages in Java. So first click here to get the basic idea of Java packages. Once you finish reading that, you can get back to this guide.

Previous Topic: Use of this Keyword In Java

Access Modifiers in Java

Access modifiers in Java are reserved-keywords that are used to define the visibility/accessibility of a class/interface and anything inside it like the data fields, methodsconstructors, etc.

The interface is a non-primitive data type in Java, just like a Java class. You can learn about Java interfaces later here.

The access modifiers in Java sets the boundary of where you can access a class and the items inside the class.

There are four access modifiers in Java.

 

Of all the four access modifiers in Java, the public access modifier gives the most visibility.

The protected access modifier comes second, the default access modifier is third, and the private access modifier comes last.

The private access modifier has the least visibility.

Where should I place the access modifiers in a Java program?

1. For primitive and non-primitive data types, put the keyword before the data-type.

Example:

public class Geeky {
	public int i;
	protected float j;
	long k; // default access modifier: no keyword
	private String s;
}

2. For methods, add the keyword before the return type.

Example:

public class Geeky {

	public void methodOne() {}

	protected void methodTwo() {}

	void methodThree() {} // default access modifier: no keyword

	private void methodFour() {}
}

3. For class constructors, there is no return type, so put the keyword before the constructor name.

Example:

public class Geeky {

	private Geeky() {} //private constructor
}

I will explain the public access modifier first. Let’s go from the most visible one to the least visible.

Public Access Modifier

As I mentioned above, the public access modifier provides the most visibility.

If you give the public access modifier to a class, it simply means you can access it from anywhere in the application.

Anything that is public in Java is accessible everywhere.

Now let’s see what this ‘everywhere‘ actually means.

To easily understand it, as I suggested earlier, you must read about the Java packages first.

If you have already read it, you would know that, In Java, we organize Java classes in packages (just think of a package as a folder, because that’s what it is).

So, if you declare a class inside a package as public as below, it will be visible to all the other classes in the current package and the other packages in a Java application.

public class Geeky {
}

For example, imagine you create a Java application. Let’s say the application name is ‘GeekyApp‘.

Now, inside the ‘GeekyApp’ you create three Java packages: pkgone, pkgtwo, and pkgthree.

Inside the pkgone, you create a class named ‘Geeky‘.

package pkgone;
public class Geeky {
}

As you can see, ‘Geeky‘ is a public class.

Imagine, the other packages (pkgtwo and pkgthree) have some Java classes in them.

Here, all the classes inside the GeekyApp can access the ‘Geeky‘ class.

The other classes could be inside any of the three packages, i.e., the pkgone (current package), pkgtwo, or the pkgthree package.

All you need to understand from this is that if there is something public inside a Java application, it is accessible everywhere in the application.

This ‘something’ could be a class or an interface or anything inside them (methods, fields, constructors, etc.), and this ‘everywhere’ means from every package of the application.

But there is an exception to this.

Look at the below program.

class Geeky {
	public int num;
}

In this program, you can see the instance variable ‘num‘ of the class ‘Geeky‘ is public.

Public means it is available everywhere in the program. Right?

But in the above program, it is not right.

Why?

Simple. Here the class Geeky is not public. This means it is not visible everywhere.

In order to access anything inside a class, you must be able to access the class first.

The visibility of a class takes precedence over the visibility of its components.

The same applies to interfaces as well.

So, wherever you can access a class, only there you can access the components of the class.

Now, you may ask, “So, is there no point in giving public access modifier only to the components of a class and not to the class itself?“.

Of course not.

It is like locking someone inside a room and giving him the keys to all the rooms.

What can he do with the keys if he can’t get out of the room?

Got it. Right?

If the class is public, then it makes sense to give public access modifier to the components of the class.

Just because a class is public, it doesn’t mean that you can access its components everywhere.

You must define the visibility of each component individually.

For example, a class can be public, and its components can be private, protected, default, or public. It’s your choice.

One important point related to this is that if the class is public, then the class name and the source file name must be the same.

Let’s move on to the second Java access modifier.

Protected Access Modifier

The protected access modifier is one step below the public access modifier in Java.

The first point you must learn is that you cannot make a class protected in Java.

Java classes support only two of the access modifiers. One is public, which you learn before. The second is the default access modifier, which you will learn next.

You cannot make a class protected, but you can make anything inside a class protected.

The protected items of a class are:

  • Visible to all the classes inside the current package.
  • Visible only to the child classes in other packages.

Note the second point.!

It is the difference between the public access modifier and the protected access modifier.

Check out the program below.

package packageone;

public class Geeky {

	protected String name;

	protected Geeky() {
	}

	protected void display() {
		System.out.println("The name is: " + name);
	}
}

Above, we have the public class ‘Geeky‘ with all the components declared as protected.

The instance variable ‘name‘, the class constructor, and the method ‘display()‘ are protected.

If you look at the first line of the program, you can see that the Geeky class is in a package named ‘packageone‘.

Now, let’s create another class in the same package and access all the protected members of Geeky.

package packageone;

public class Point {

	public static void main(String[] args) {
		Geeky geeky = new Geeky();
		geeky.name = "GeekyPoint";
		geeky.display();
	}

}

We have a class named ‘Point‘ in the same package.

In this class, I do three things,

  • Call the Geeky class constructor to create the object
  • Access the instance variable ‘name‘ of Geeky class and assign the string “Geeky Point
  • Call the ‘display()‘ method of Geeky class to print the value of ‘name

OUTPUT:

The name is: GeekyPoint

This is the case of classes within the same package.

The protected makes no restriction on the classes in the same package.

It makes a restriction only for the otherpackage classes.

It allows only the child classes of our class stored in other packages to access the protected elements.

We can say that it is protecting our class components from the unconnected classes in other packages.

By unconnected classes, I mean the classes which are not the child of our class.

Now you might think, “what is this child class?“.

The child class is a term that comes in the concept of inheritance in Java.

Inheritance is one of the most important Object-oriented programming (OOPs) concepts in Java.

For you, I will briefly explain the concept of inheritance now. You can expect a detailed explanation of ‘Inheritance in Java‘ in another upcoming tutorial.

In Java, a class can acquire the properties and behavior of another class. This is what inheritance is.

To understand it better, let’s take two classes, class A and class B.

class A {

}

class B {
	
}

Let’s imagine that class B is the child of class A.

To define that in Java, you need to use a keyword called ‘extends‘.

See the program below.

class A {
}

class B extends A {
}

The keyword ‘extends’ simply means that class B inherits the properties and behaviors of class A.

Here B is the child class, and A is the parent class.

Currently, there is nothing inside these classes.

Let’s add a field and method to class A and see how to access them in the child class.

public class A {
	protected int num;

	protected void printNum() {
		System.out.println("Value of num is: " + num);
	}
}

public class B extends A {
	public static void main(String[] args) {
		B child = new B();
		child.num = 20;
		child.printNum();
	}
}

OUTPUT:

Value of num is: 20

In the above program, inside the main method, I create the object of the child class B.

With the class B object, I access the instance variable of class A and call the instance method of A.

What you see here is that a child inherits from its parent.

This is simply the basis of inheritance in Java, and you see it in the above program.

In the above program, the components of class A (the instance variable ‘num‘ and the method ‘printNum()‘) use the protected access modifier.

Therefore, the child class B can access them, no matter whether B and A are in the same package or not.

Hope you understood the use of the protected access modifier.

Now, let’s move on to the third access modifier.

Default Access Modifier

The default access modifier has no keyword.

The default access modifier is also known as ‘friendly‘.

‘Friendly’ is not a Java keyword, it is just a term developers use to refer to the default access modifier.

If you don’t add any other access modifier while defining a class or the members of the class, it is treated as default.

The visibility of the default access modifier is within the current package only.

If a class in a package has the default accessibility, only the other classes in that package can access it.

Anything with the default visibility won’t be visible outside its package.

Because of this, the default access modifier is also known as ‘package-private‘.

You can call it friendly, default, or package-private as you wish.

Example:

package packageone;

class Geeky {

	int age;

	Geeky() {
	}

	void display() {
		System.out.println(age);
	}
}

In this program, as you can see, I have given no other access modifier to the class and its components.

Therefore, the class ‘Geeky‘, the variable ‘age‘, the class constructor, and the method ‘display()‘ have the default accessibility.

The class is inside the package ‘packageone‘.

All the other classes in the packageone can see and access the Geeky class.

Geeky class is invisible to all the classes in other packages.

Let’s move on to the fourth access modifier.

Private Access Modifier

The last and also the least visible of all the access modifiers in Java is private.

You cannot make a class private in Java, but you can make anything inside the class private, similar to the protected access modifier.

The visibility of a private item is within the class only. 

No other classes can access the private components of a class.

They are private to their class.

Not even the child classes can access them.

Maybe you can use your own logic to let others use the private components of your class indirectly.

Direct access to the private items of a class is not possible in Java.

Example:

package packageone;

public class Geeky {

	private int id;

}

In the above program, the variable ‘id‘ is private to the Geeky class.

Now let’s try to access it from another class.

package packageone;

public class TestPrivate {

	public static void main(String[] args) {
		Geeky geeky = new Geeky();
		geeky.id = 369; // invalid
	}

}

In this class, the last line geeky.id = 369; is invalid.

It will throw a compile-time error that says ‘The field Geeky.id is not visible‘.

 

If you choose to let other classes of your program access the private variable ‘id‘, you can define two public methods as below.

package packageone;

public class Geeky {

	private int id;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
}

This is a common way to encapsulate the data fields of a class in Java.

Now you can use the ‘setId()‘ and ‘getId()‘ methods to set and get the value of the private field ‘id‘.

See the program below.

package packageone;

public class TestPrivate {

	public static void main(String[] args) {
		Geeky geeky = new Geeky();
		geeky.setId(369);
		System.out.println("The Id is: " + geeky.getId());
	}

}

OUTPUT:

The Id is: 369

 

Now, you know that the private members of a class have the least visibility in Java.

But is there anything else in Java, which is less visible than private?

The answer is yes.

No, no, I am not talking about any other undiscovered Java access modifiers, because there aren’t any.

I am talking about the local variables in Java.

Local variables are less visible than the private members of a class.

Local variables are declared inside the sub-blocks of a class, and they are visible inside that block only.

You can’t add any access modifiers in Java to local variables.

As the name suggests, they are local; they are meant to be used locally.

You can learn more about local variables here.

The below image briefly shows the access boundaries of all the four access modifiers in Java.

 

Conclusion

Well, in this guide, I described the use of the four access modifiers in Java with examples.

Do you like the way I explained it?

Is there anything you wish I must add to this guide?

Let me know all your thoughts about this guide with a quick comment.

Thanks for dropping by.

I hope you find this guide helpful.!

Leave a Reply

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