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.

Encapsulation sample code
package in.ihelpyou;

class Student {

	int studRollNo;
	int studAge;
	String studName;

	public Student(int rollno, int age, String name) {
		studRollNo = rollno;
		studAge = age;
		studName = name;
	}

	public int getAge() {
		return studAge;
	}

	public String getName() {
		return studName;
	}

	public void setAge(int age) {
		studAge = age;
	}

	public void setName(String name) {
		studName = 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);
		student2.setName("Lakshmi S");

		System.out.println("Student1 age: " + student1.getAge());
		System.out.println("Student2 name: " + student2.getName());
	}

}