Tech Master Tutorials
Email Facebook Google LinkedIn Pinterest Twitter
Home Java Java 8 Java Interview Questions Java8 Interview Questions Object Oriented Programming in Java JVM Java Programming

Encapsulation

Encapsulation is combining fields and methods together into a class.
Or we can say that combining state and behavior into a class.

In Java, fields and methods are encapsulated together and with that we can mark fields private and can provide access through only public methods. That way fields can not be updated accidentally like C/C++ where we hgave global variables.


Below is the Student class that encapsulates the student state and behaviours.
package oops.encapsulation;

public class Student {
	private int rollNumber;
	private String name;

	public int getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
In the abovce example, Student class defines states rollNumber and name, and setter/getter methods are provided around it that are the behavious of student class.
Student class allows to set or get the states.
If you look at the example, both states are private that means that they can not be accessed with the class reference,
these states can only be accessed through public methods provided in the class.
This solves the problem of modifying the states accidentally, like accidental modification can happen
in case of global variables in C/C++.