Syntax of Private Variable
private type varName = value;
type is any data type in java.
varName is any valid identifier in java. It is a variable name.
value is an optional. You can initialize variable by assigning its value.
Example of Private Variable
Example 1 : Program that illustrates private variable use in java using employee class salary variable
class Employee
{
String empName;
private int salary; // It is visible in Employee class only
public Employee(String strEmp)
{
empName = strEmp;
}
public void setSalary(int empSlr)
{
salary = empSlr;
}
public void displayDetail()
{
System.out.println("Employee Name : " + empName);
System.out.println("Employee salary :" + salary);
}
}
class PrivateVariableDemo
{
public static void main(String args[])
{
Employee empObj = new Employee("Rayan");
empObj.setSalary(5000);
empObj.displayDetail();
}
}
Output
Employee Name : Rayan
Employee salary :5000