Java Tut – Encapsulation

Encapsulation is one of the four fundamental OOP concepts.The other three are inheritance,polymorphism and abstraction.

it is a mechanism of wrapping the data variables and code acting on the data together as single unit. In encapsulation teh variables of a class will be hidden from other classes and can be accessed only through the methods of their current class, therefore it is also known as data hiding.
To achieve-

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


public class EncapTest {
private String name;
private String idNum;
private int age;

public int getAge()
	return age;

public String getIdNum(){
	return idNum;

public void setAge(int newAge)

public void setName(String newName)

public void setIdNum(String newId)


the public setXXX() and getXXX() ethods are the access points of the instance variables of the EncapTest class.Normally these methods are referred as getters and setetrs.Therefore any class that wants to access teh variables should access them through these getters and setters.

public class RunEncap {
public static void main(String[] args)
	EncapTest encap=new EncapTest();
	encap.setName("James Gosling");
	System.out.print("Name: "+encap.getName()+"Age:"+encap.getAge());


Name: James Gosling Age:20




It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

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