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:
- Make class as public or non abstract
- Make instance variable as private
- Create Getter and Setter method for respective instance variable
Advantages of encapsulation in java
List of advantages of encapsulation in java is given below:
- We can perform data validation
- We can protect data members
- 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