0% found this document useful (0 votes)
3 views8 pages

Java Access Modifiers

Java Access Modifiers control the visibility and accessibility of classes, methods, and variables. There are four types of access modifiers: private, default, protected, and public, each with specific access levels. Best practices suggest using private for encapsulation, default for package-level access, protected for inheritance, and public for global access.

Uploaded by

dhruvv060606
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Java Access Modifiers

Java Access Modifiers control the visibility and accessibility of classes, methods, and variables. There are four types of access modifiers: private, default, protected, and public, each with specific access levels. Best practices suggest using private for encapsulation, default for package-level access, protected for inheritance, and public for global access.

Uploaded by

dhruvv060606
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Access Modifiers

Understanding Java's Access Control


Mechanism

Designed By : Dr Sandeep Monga


What are Java Access Modifiers?
• Access Modifiers in Java control the visibility
and accessibility of classes, methods, and
variables.

Designed By : Dr Sandeep
Monga
Types of Java Access Modifiers
Java Access Modifiers:

Modifier Class Package Subclass World


private Yes No No No
default (no Yes Yes No No
modifier)
protected Yes Yes Yes No
public Yes Yes Yes Yes

Designed By : Dr Sandeep
Monga
Private Modifier
Accessible only within the same class
Not accessible in subclass or outside the class

Example:
class Example {
private int data = 10;
private void show() {
[Link]("Hello");
}
}

Designed By : Dr Sandeep
Monga
Default (No Modifier)
Accessible within the same package only
Cannot be accessed from another package

Example:
class Example {
void display() {
[Link]("Hello");
}
}

Designed By : Dr Sandeep
Monga
Protected Modifier
Accessible within the same package and
subclasses in other packages
Allows inheritance access

Example:
class Parent {
protected void display() {
[Link]("Hello");
}
}
Designed By : Dr Sandeep
Monga
Public Modifier
Accessible everywhere (same package &
different packages)

Example:
public class Example {
public void display() {
[Link]("Hello");
}
}
Designed By : Dr Sandeep
Monga
Summary & Best Practices
Use private for encapsulation
Use default for package-level access
Use protected for inheritance-based access
Use public for global access

Designed By : Dr Sandeep
Monga

You might also like