Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Private Variable

Posted By: Rashad Hashmi     Category: Java     Views: 2866

This article explains about private variable in java with example.

Private variables can be accessed only by code in the same class. If you want to set/get value of that variable than you need to call privileged methods.    

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

  
Share: 

 
 
 

Didn't find what you were looking for? Find more on Private Variable Or get search suggestion and latest updates.

Rashad Hashmi
Rashad Hashmi author of Private Variable is from Lahore, Pakistan.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!