Java Encapsulation

Java Encapsulation:

We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it.

Encapsulation is a mechanism that binds class members (variables and methods) together and protects them from being accessed by the other classes. In Java, you can consider a class as an example of encapsulation, because a class binds data and code together and hides their complexity from other classes. We can create a fully encapsulated class in Java by making all the data members of the class private.

Note: (1) Declare the class variables as private.
(2) Provide public setter and getter methods to modify and view the variables values.

In class we define the objects and methods. We call these objects and methods in class as shown below. Class:

java student class encapsulation code 1
public class Student {
	private String stu_name;
	private int stu_age;
	private double stu_marks;
	private String stu_city;
	Student (String stu_name, int stu_age, double stu_marks, String stu_city){
	public String getStudentName() {
		return stu_name;
   public int getStudentAge() {
		return stu_age;

   public double getStudentMarks() {
	return stu_marks;

   public String getStudentCity() {
	return stu_city;
   public void setStudentName(String stu_name) {
		this.stu_name = stu_name;
   public void setStudentAge(int stu_age) {
		this.stu_age = stu_age;
   public void setStudentMarks(double stu_marks) {
		this.stu_marks = stu_marks;
   public void setStudentCity(String stu_city) {
		this.stu_city = stu_city;
} Class:

main java class encapsulation example
public class Main {
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	  Student student = new Student("Andrew", 25, 91.50, "New York");
	  // Example of Setter Method
	  //Example of getter method
	  System.out.println("Age is " + student.getStudentAge() + " years old");
	  System.out.println("Marks = " + student.getStudentMarks());


Tutorial MySQL
Tutorial Python
Internet and Its Uses
World Wide Web (WWW)
Malicious Software (Malware)
Database Management System (DBMS)
Chr and Ord Function in Python
List Comprehension in Python
Implement Queue in Python
Java (programming language)– Wikipedia

Comments (No)

Leave a Reply