# 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:

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTGykQTeg0OGCFzGzEH%2F-LTH5kEyrbLKv4yj5tAS%2FaccessModExampe.png?alt=media\&token=301c497e-90fd-4829-a195-e4248c08e793)

\
Public: Anyone can see your profile

Protected : Only your friends

Default: Only specific user group

Private : Only me

### &#x20;**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&#x20;

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

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHEM6kWTPDoO0A7Vxu%2F-LTHF2a23SdNUUiePd5O%2FScreen%20Shot%202018-12-09%20at%202.44.56%20PM.png?alt=media\&token=85e96eb8-b547-4c3c-ab6c-db555cad55fc)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHEM6kWTPDoO0A7Vxu%2F-LTHFARJBB2PXar7bHsJ%2FScreen%20Shot%202018-12-09%20at%202.45.03%20PM.png?alt=media\&token=12a11645-6861-40d8-82c9-9e3f6db4ef7e)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHEM6kWTPDoO0A7Vxu%2F-LTHFEpes4wl8ePgMTK3%2FScreen%20Shot%202018-12-09%20at%202.45.08%20PM.png?alt=media\&token=f29fb6c9-f25a-455f-9709-27f97513a264)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHEM6kWTPDoO0A7Vxu%2F-LTHFHrB8b2G9DEoZAKn%2FScreen%20Shot%202018-12-09%20at%202.45.21%20PM.png?alt=media\&token=2cb3f593-c588-4d81-bc1c-22b0321fccaa)

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

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHEM6kWTPDoO0A7Vxu%2F-LTHFx9RAqKA1Kc2l2cj%2FScreen%20Shot%202018-12-09%20at%202.49.19%20PM.png?alt=media\&token=f6d4bbe5-7ad5-4029-8f36-bfbf53599694)

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.

```java
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:

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

![Classes from the same and separate packages](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHAAj2QcP4s8qumh_T%2F-LTHANZa-6Vc7zq2E6xB%2FScreen%20Shot%202018-12-09%20at%202.24.58%20PM.png?alt=media\&token=1ec83927-8f6b-4623-8a06-8ac6a4269ba9)

**DEFINING A CLASS BOOK WITH DEFAULT ACCESS:**

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHAAj2QcP4s8qumh_T%2F-LTHCIARAb692Us7skHA%2FScreen%20Shot%202018-12-09%20at%202.31.46%20PM.png?alt=media\&token=4156d7ca-301a-40ce-9655-92b8f4b656f1)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHAAj2QcP4s8qumh_T%2F-LTHCMGr4ZctwXeUtADN%2FScreen%20Shot%202018-12-09%20at%202.32.00%20PM.png?alt=media\&token=99e766d1-84bf-4714-8c0e-aed255cf6ced)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTHAAj2QcP4s8qumh_T%2F-LTHCV6iOFBHGRUngAT9%2FScreen%20Shot%202018-12-09%20at%202.32.15%20PM.png?alt=media\&token=90964de0-cc87-4bdb-8016-077507cd80c8)

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

```java
//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

![Access of protected members of the class Book in unrelated and derived classes, from the same and separate packages](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTH8YV6hGwFYZdWNxAv%2F-LTH8wy2-x9gnBtVaDkS%2FScreen%20Shot%202018-12-09%20at%202.18.33%20PM.png?alt=media\&token=f15aa7d0-d869-41f1-995f-b9cefb989c69)

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

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTH99fQV25c41anFx1Y%2F-LTH9Op84gyVudpBHx5r%2FScreen%20Shot%202018-12-09%20at%202.20.45%20PM.png?alt=media\&token=33b82099-5d92-45ac-b847-3af75c7e8562)

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

```java
//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.

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTH68cre54_Hj5tE6qM%2F-LTH6ZYdm4ABv-tK84u5%2FScreen%20Shot%202018-12-09%20at%202.08.19%20PM.png?alt=media\&token=66a6bfcd-6abe-4afa-a707-6e6000a063d8)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTH68cre54_Hj5tE6qM%2F-LTH7Ji9cC3yA5vGaWti%2FScreen%20Shot%202018-12-09%20at%202.10.49%20PM.png?alt=media\&token=2913c98b-2995-4dba-8554-fbb5f6d66692)

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTH68cre54_Hj5tE6qM%2F-LTH7kaVoTUPBBpUg_ui%2FScreen%20Shot%202018-12-09%20at%202.13.24%20PM.png?alt=media\&token=b24206fd-350e-401d-915e-db880a6bfef3)

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

**NOTE :**&#x54;he 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**

```java
//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&#x20;

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

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gyansetu-java.gitbook.io/core-java/access-modifiers.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
