No announcement
 

Encapsulation

Encapsulation is the wrapping of the data variables and methods together as a single unit. The variables of a class are hidden from other classes by declaring them as private and is made accessible through their respective getter (for getting the value) and setter (for setting the value) method.

Example:

EncapsulationDemo.java

package com.codingnous.tutorial;

public class EncapsulationDemo {

	public static void main(String[] args) {

		// Create class object
		Student s = new Student();

		// Set name.
		s.setName("John Doe");

		// Set total marks.
		s.setTotalMarks(475);

		// Fetch name.
		System.out.println("Student name: " + s.getName());

		// Fetch total marks.
		System.out.println("Marks obtained: " + s.getTotalMarks());

		// Alternatively invoke another method.
		System.out.println(s.Detail());

	}

}

class Student {

	private String name;
	private int totalMarks;

	// Getter method for name.
	public String getName() {
		return name;
	}

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

	// Getter method for totalMarks.
	public int getTotalMarks() {
		return totalMarks;
	}

	// Setter method for totalMarks.
	public void setTotalMarks(int totalMarks) {
		this.totalMarks = totalMarks;
	}

	// Another method for returning details.
	public String Detail() {
		return (name + " has obtained " + totalMarks + " marks");
	}

}

Output
Student name: John Doe Marks obtained: 475 John Doe has obtained 475 marks