Menu Close

Access private variables in Java

  • One object cannot access the private information of another object directly.
  • We can access the private data in communication using methods.
  • The two standard method using in communication is called getter(get) and setter(set)
  • get() is used to collect the information on request.
  • set() is used to send the information on request.
  • Static variables having static get and set methods.
  • Instance variables access with non static get and set methods.

Access static variable using get():

class First 
{
	private static int x = 10 ;
	static int getX()
	{
		return First.x ;
	}
}
class Second
{
	public static void main(String[] args) 
	{
		// System.out.println("x val : " + First.x);  -> Error : private access
		System.out.println("x val : " + First.getX());   // allowed
	}
}

Accessing instance variables using get():

class First 
{
	private int x ;
	First(int x)
	{
		this.x = x ;
	}
	int getX()
	{
		return this.x ;
	}
}
class Second
{
	public static void main(String[] args) 
	{
		First obj = new First(10) ;
		// System.out.println("x val : " + obj.x);  -> Error : private access
		System.out.println("x val : " + obj.getX());
	}
}

Modify value to private static variable using set():

class First 
{
	private static int x = 10 ;
	static int getX()
	{
		return First.x ;
	}
	static void setX(int x)
	{
		First.x = x ;
	}
}
class Second
{
	public static void main(String[] args) 
	{
		System.out.println("x val : " + First.getX());
		First.setX(20);
		System.out.println("x val : " + First.getX());
	}
}

Modify value to private non-static variable using set():

class First 
{
	private int x ;
	First(int x)
	{
		this.x = x ;
	}
	int getX()
	{
		return this.x ;
	}
	void setX(int x)
	{
		this.x = x ;
	}
}
class Second
{
	public static void main(String[] args) 
	{
		First obj = new First(10) ;
		System.out.println("x val : " + obj.getX());

		obj.setX(20);
		System.out.println("x val : " + obj.getX());
	}
}
  • Class cannot be private.
  • Class represents Object.
  • If the complete class is private, Object is not accessible in application.
  • We define objects for communication.
private class Test 
{
	public int x ;
	private int y ;
}