Encapsulation in java

What you will learn here about encapsulation of java

  • Encapsulation in java
  • How to achieve encapsulation in java
  • Advantages of encapsulation in java
  • Encapsulation example in java

Encapsulation in java

Encapsulation is the process of wrapping or binding the data members along with data handler methods. The getter and setter methods are the data handler methods.

Encapsulation is called as data hiding.

How to achieve encapsulation in java

Steps to achieve encapsulation in java are given below:

  1. Make class as public or non abstract
  2. Make instance variable as private
  3. Create Getter and Setter method for respective instance variable

Advantages of encapsulation in java

List of advantages of encapsulation in java is given below:

  1. We can perform data validation
  2. We can protect data members
  3. We can make data members read only or write only or both

Encapsulation example in java


//make class public
public class Student {
	
	//make variable private
	private String name;
	
	private int roll_number;

	public static void main(String[] args) 
	{
		Student s=new Student();
		
		//set variables using setter method
		s.setName("John");
		s.setRoll_number(20);
		
		//get data using getter method
		System.out.println("Name is : "+s.getName()+" and roll number is "+s.getRoll_number());
		
	}

	//Getter and Setter methods 
	
	public String getName() {
		return name;
	}

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

	public int getRoll_number() {
		return roll_number;
	}

	public void setRoll_number(int roll_number) {
		this.roll_number = roll_number;
	}
	

}


OUTPUT

Name is : John and roll number is 20

You may also like...