Wednesday, Jul 15, 2026 · Practical tutorials, weekly

What is encapsulation in java | Java Encapsultion | Getters and Setters

S Saurabh K Jul 17, 2020 1 min read 0 comments

Java Encapsulation

Encapsulation is defined as the wrapping up of data under a single unit.
Example: A capsule which is mixed of several medicines. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. That’s why it is also known as data hiding.

How we can achieve encapsulation in java?

  1. Declare the variables of a class as private.
  2. Provide public setter and getter methods to modify and view the variables values.

Example Program for Encapsulation:

class EncapPro{
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}

public String getName() {
return name;
}

public String getIdNum() {
return idNum;
}

public void setAge( int newAge) {
age = newAge;
}

public void setName(String newName) {
name = newName;
}

public void setIdNum( String newId) {
idNum = newId;
}
}

public class RunEncapPro {
public static void main(String args[]) {
EncapPro encap = new EncapPro();
encap.setName(“Technical Speaks”);
encap.setAge(1000);
encap.setIdNum(“0123abc”);
System.out.print(“Name : ” + encap.getName() + ” Age : ” + encap.getAge());


}
}

Output: Name: Technical Speaks   Age: 1000

This, Super and Final keywords in Java

Connect with us:

Share:
Saurabh K

Saurabh K

Author at Technical Speaks

Writes practical guides and tutorials to help readers build, rank, and grow online.

Leave a Comment

Newsletter

Stay ahead of the curve

Join readers getting our freshest tutorials and guides on web, SEO, tech & more — delivered weekly.