Skip to main content

← Back to Overview

Java Program - Encapsulation (Private Members)

Concept Explanation

What is it?

Encapsulation is one of the four fundamental OOP concepts. It involves bundling the data (variables) and the methods that act on the data into a single unit (class) and restricting direct access to some of an object's components.

Why is it important?

It protects data from accidental corruption. By making fields private and providing public methods to access them, you can control how fields are accessed or modified (e.g., preventing a negative age).


Implementations

class Student {
// Private variables (Data Hiding)
private int id;
private String name;

// Public Getter for ID
public int getId() {
return id;
}

// Public Setter for ID with Validation
public void setId(int id) {
if (id > 0) {
this.id = id;
} else {
System.out.println("Error: Invalid ID. Must be positive.");
}
}

// Public Getter for Name
public String getName() {
return name;
}

// Public Setter for Name
public void setName(String name) {
this.name = name;
}
}

public class EncapsulationDemo {
public static void main(String[] args) {
Student s1 = new Student();

// s1.id = 101; // Compile Error: id has private access

s1.setId(101);
s1.setName("Alice");

System.out.println("Student ID: " + s1.getId());
System.out.println("Student Name: " + s1.getName());

// Test Validation
s1.setId(-5); // Will print error message
}
}

Explanation

  • Private Fields: id and name cannot be accessed directly by other classes.
  • Public Methods: getId() and setId() provide a controlled interface.
  • Logic in Setters: The setId method checks if the input is valid before assignment. This logic would be impossible with direct public field access.


"Encapsulation is the first step towards a robust and secure design." - Anonymous

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir