Java Encapsulation

Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It is the process of wrapping data (fields) and methods (behavior) together into a single unit (class) and restricting direct access to them. Instead, access is provided through public methods, known as getters and setters.


In Java, encapsulation is implemented by:

  1. Declaring fields as private.
  2. Providing public getter and setter methods to access and update the values of the fields.


Example
class Human{
private int age; // private = restricted access

// Getter
public int getAge(){
return age;
}

// Setter
public void SetAge(int a){
age=a;
}
}

public class Main {
public static void main(String[] args){
Human obj=new Human();
obj.SetAge(30);
System.out.println("Name : "+obj.getAge());
}
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.