private modifier in java

Previous
Next

private:

  • Private members belong to particular object. These members are completely hidden from outside world.
  • Private members of class can be accessed only within that class in which those are defined.
public class First
{
	public static int a=10;
	private static int b=20;
	public static void main(String args[ ])
	{
		System.out.println("a value : " + First.a);
		System.out.println("b value : " + First.b);
	}
}

Accessing private members from another class:

  • Private members of class cannot be accessed from another class directly.
  • Attempting to access results error.
class First
{
	public static int a=10;
	private static int b=20;
}
public class Second
{
	public static void main(String args[ ])
	{
		System.out.println("a value : " + First.a);
		System.out.println("b value : " + First.b);  // Error : private access
	}
}

Question: How to access private members of another class?

  • Generally one real world object(class) data is always private.
  • Other objects(classes) cannot access private data.
  • Communication is the process of sharing the private information.
  • One object can request another object to get private data.
  • The two standard methods given to send and receive the private data
    • Set() : used to set values
    • Get(): used to get values
class First
{
	private static int x = 10;
	static int getX()
	{
		return First.x ;
	}
}
public class Second
{
	public static void main(String args[ ])
	{
		// System.out.println("x value : " + First.x); -> Error : No direct access
		System.out.println("x value : " + First.getX()); // access in communication
	}
}

We need to define get method for each variable defined in class.

class Emp
{
	private static int id = 101;
	private static String name = "Amar" ;
	private static double salary = 30000 ;
	public static int getId()
	{
		return Emp.id;
	}
	public static String getName()
	{
		return Emp.name;
	}
	public static double getSalary()
	{
		return Emp.salary;
	}
}

public class Access
{
	public static void main(String args[ ])
	{
		System.out.println("Emp ID : " + Emp.getId()); 
		System.out.println("Emp Name : " + Emp.getName()); 
		System.out.println("Emp Salary : " + Emp.getSalary()); 
	}
}
Previous
Next

Add Comment

Courses Enquiry Form