18) Access Modifiers

What are Access Modifiers?

Access modifiers control the accessibility of a class or an interface, including its mem-bers (methods and variables), by other classes and interfaces within the same or separate packages. By using the appropriate access modifiers, you can limit access to your class or interface and their members.

Java has four access levels:

  1. public (least restrictive)

  2. protected

  3. default

  4. private (most restrictive)

Real Life Example:

Public: Anyone can see your profile

Protected : Only your friends

Default: Only specific user group

Private : Only me

Access Modifiers Detail

Access modifiers help you set the level of access you want for your Class, variables as well as Methods.

The access modifiers in java specify accessibility (scope) of a data member, method, constructor or class.

There are 4 types of java access modifiers:

  1. Private

  2. Default

  3. Protected

  4. public

1) private access modifier

The private access modifier is accessible only within class.

The private access modifier is the most restrictive access modifier. The members of a class defined using the private access modifier are accessible only to themselves. It doesn’t matter whether the class or interface in question is from another package or has extended the class—private members are not accessible outside the class in which they’re defined. private members are accessible only to the classes and interfaces in which they’re defined.

NOTE: For your real projects, it is possible to access private members of a class outside them, using Java reflection.

NOTE: Although the package-private access is as valid as the other access lev- els, in real projects it often appears as the result of inexperienced developers forgetting to specify the access mode of Java components.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is compile time error.

package com.gs.ilp.corejava.accessModifier;

public class A {
	private int data = 40;

	private void msg() {
		System.out.println("Hello java");
	}
}

public class Simple {
	public static void main(String args[]) {
		A obj = new A();
		System.out.println(obj.data);
		// Compile Time Error
		obj.msg();
		// Compile Time Error
	}
}

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:

package com.gs.ilp.corejava.accessModifier;

class A {
	private A() {
	}// private constructor

	void msg() {
		System.out.println("Hello java");
	}
}

public class Simple {
	public static void main(String args[]) {
		A obj = new A();// Compile Time Error
	}
}

Note: A class cannot be private or protected except nested class.

2) default access modifier

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package.

The members of a class defined without using any explicit access modifier are defined with package accessibility (also called default accessibility). The members with package access are only accessible to classes and interfaces defined in the same package. The default access is also referred to as package-private.

DEFINING A CLASS BOOK WITH DEFAULT ACCESS:

Conclusion:

Default access can be compared to package-private (accessible only within a package), and protected access can be compared to package- private + kids (“kids” refer to derived classes). Kids can access protected methods only by inheritance and not by reference (accessing members by using the dot operator on an object).

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.

//save by A.java  
package pack;  
class A {  
void msg() { System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
class B{  
public static void main(String args[]){  
 A obj = new A();//Compile Time Error  
 obj.msg();//Compile Time Error  
}  
}  

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

3) protected access modifier

The protected access modifier is accessible within package and outside the package but through inheritance only.

Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

The members of a class defined using the protected access modifier are accessible to

  • Classes and interfaces defined in the same package

  • All derived classes, even if they’re defined in separate packages

Conclusion:

A concise but not too simple way of stating the previous rule is this: A derived class can inherit and access protected members of its base class, regardless of the package in which it’s defined. A derived class in a separate package can’t access protected members of its base class using reference variables.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java  
package pack;  
public class A{  
protected void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
class B extends A{  
public static void main(String args[]){  
 B obj = new B();  
 obj.msg();  
}  
}

Output:Hello

4) public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

This is the least restrictive access modifier. Classes and interfaces defined using the pub- lic access modifier are accessible across all packages, from derived to unrelated classes.

In the preceding example, class Book and its public member instance variable isbn and method printBook are accessible to class House.

NOTE :The term unrelated classes in this chapter refers to classes that don’t share inheritance relation. For instance, classes House and Book are unre- lated, if neither House derives from Book nor Book derives from House.

Example of public access modifier

//save by A.java  
package pack;  
public class A {  
public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
class B{  
public static void main(String args[]){  
A obj = new A();  
obj.msg();  
}  
}  

Output: Hello

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.

Access Modifier

within class

within package

outside package by subclass only

outside package

Private

Y

N

N

N

Default

Y

Y

N

N

Protected

Y

Y

Y

N

Public

Y

Y

Y

Y

Java access modifiers with method overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

package com.gs.ilp.corejava.accessModifier;

class A {
	protected void msg() {
		System.out.println("Hello java");
	}
}

public class Simple extends A {
	void msg() {
		System.out.println("Hello java");
	}

	// compile time Error
	public static void main(String args[]) {
		Simple obj = new Simple();
		obj.msg();
	}
}

The default modifier is more restrictive than protected. That is why there is compile time error.

Last updated