Access Modifiers and Encapsulation in Java
π Access Modifiers and Encapsulation in Java
In Java, access modifiers and encapsulation are key concepts used to control access to classes, variables, and methods, and to help write secure, maintainable code.
πΉ What is Encapsulation?
Encapsulation is the practice of hiding the internal details of an object and only exposing what’s necessary.
It’s done by:
Making variables private
Providing public getter and setter methods to access and update those variables
π Example:
java
Copy
Edit
public class Person {
private String name; // Hidden from outside classes
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
✅ Benefits of Encapsulation:
Protects data from unauthorized access
Makes the code easier to maintain and debug
Allows validation before changing a value
Improves modularity and reusability
πΉ What are Access Modifiers?
Access modifiers define the visibility (access level) of classes, methods, and variables.
Java has four main access modifiers:
Modifier Access Level Where it's Accessible From
public Open to all Any class in any package
private Most restricted Only within the same class
protected Limited + inheritance Same package + subclasses in other packages
No modifier (default) Package-private Only within the same package
π Examples:
public
java
Copy
Edit
public class Car {
public void drive() {
System.out.println("Driving...");
}
}
Anyone can call drive() from any class.
private
java
Copy
Edit
public class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public double getBalance() {
return balance;
}
}
balance is hidden and only accessed via methods.
protected
java
Copy
Edit
public class Animal {
protected void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
public void bark() {
makeSound(); // Allowed because it's inherited
}
}
No Modifier (Package-private)
java
Copy
Edit
class PackageHelper {
void help() {
System.out.println("Helping...");
}
}
Only classes in the same package can use help().
π§ Summary
Concept Purpose
Encapsulation Hides internal details of a class
Access Modifiers Control visibility of classes, methods, fields
private Most restrictive (used for encapsulation)
public Least restrictive (used to expose methods)
protected Useful for inheritance
Default Package-level visibility
✅ Best Practices
Keep data fields private
Use getters and setters to control access
Avoid making everything public
Use protected only when extending classes
Learn Full Stack JAVA Course in Hyderabad
Read More
Understanding JVM, JRE, and JDK
Java File I/O – Read and Write Files
Multithreading and Concurrency in Java
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment