Encapsulation
In object-oriented programming (OOP), encapsulation is the concept of binding attributes (data members) and methods (functions) together as a single unit. It can be used to hide both data members and methods associated with an instantiated class or object.
package in.ihelpyou;
class Student {
// private: code outside Student cannot read or change these directly
private int rollNo;
private int age;
private String name;
public Student(int rollNo, int age, String name) {
this.rollNo = rollNo;
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
// The setter controls every change, so an invalid age can never be stored.
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
public void setName(String name) {
this.name = name;
}
}
public class School {
public static void main(String[] args) {
Student student1 = new Student(10001, 14, "Karthik");
Student student2 = new Student(10002, 14, "Lakshmi");
student1.setAge(15);
student1.setAge(-3); // ignored by setAge
student2.setName("Lakshmi S");
// student1.age = -3; // compile error: age is private
System.out.println("Student1 age: " + student1.getAge()); // 15
System.out.println("Student2 name: " + student2.getName()); // Lakshmi S
}
}
