Encapsulation in Java | OOP Fundamental Concept

Contents

Introduction  to  Encapsulation

How  to  implement  encapsulation

To achieve this, you must:

  1. declare class variables/attributes as private
  2. provide public get and set methods to access and update the value of a private variable

Get and Set Methods

e.g. If the name of the variable is student_ID, then the methods names will be

getStudentId() and setStudentId().

Example – 1

public class Person {

private String name;   // private = restricted access

 // Setter Method

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

}

 // Getter Method

public String getName() { return name;

}

}

Example – 1 explained

Example – 1 (Error) 
As the name variable is declared as private, we cannot access it from outside this class public class Person {
private String name;    // private = restricted access // Setterpublic void setName (String newName) {this.name = newName;}// Getterpublic String getName() {return name;}public class Main{public static void main(String[] args{Person myObj = new Person();myObj.name = “Jakaria”; // error System.out.println(myObj.name); // error}}           
} 
   
Example – 1 We can access the private variables with setter and getter methods of that calss.public class Person {private String name;    // private = restricted access// Setterpublic void setName (String newName) {this.name = newName;}// Getterpublic String getName() {return name;}public class Main{public static void main(String[] args{Person myObj = new Person();myObj.setName(“Jakaria”);// Set the value of the name variable to “Jakaria”System.out.println(myObj.getName());}}           // Outputs “Jakaria”    
Example – 2 
public class Person { private String name;
private int age;public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}public String getName(){return name;}public int getAge() {return age;}}public class EncapsulaionExample{public static void main(String[] args) {Person p1 = new Person(); p1.setName(“Asha”);p1.setAge(20);System.out.println(“Name: “+p1.getName())System.out.println(“Age: “+p1.getAge(}}            
// Outputs Name: Asha Age: 20 
  

[Encapsulation = Data Hiding + Abstraction]

Data Hiding: By declaring variables as private, we can achieve data hiding. we cannot access it from outside this class

Abstraction: Highlighting the service that are offering without explaining internal design/information is the concept of Abstraction.

Using ATM Card,

Example – 2

[Encapsulation = Data Hiding + Abstraction]

public class Account {

private double balance;// data hiding

public double getBalance () {

//Validation return balance;

ATM GUI

}

public void setBalance(double balance) {

//Validation this.balance = balance;

}

}

Advantage of Encapsulation

Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *