Friday, May 19, 2017

Private access modifier in Java

Private access modifier in Java


Private is the keyword in java and it is also called as the access modifier in java which defines the visibility to the members of the class like methods, constructors, variables etc. Declaring private to the members of the class will limit theirs visibility to that class only. If we are trying to access any private member in another class then compiler will give compilation error as " Member are not visible ".  

Note : We cannot use private with the class as it makes no sense making a class visible because we are accessing member of the class not the class itself. So we can be able to use private with the member of the class member.

Where we can be able to use private access modifier ?
Private access modifier can be used with the constructor, variable and methods.

Members of the class declared as private can be accessible within that class only. We have two scope in java program :-
1. Class Scope
  • Sub-class in the same package       --> Private is Not Visible .
  • Sub-class in different package        --> Private is Not Visible.
  • Another class in the same package --> Private is Not Visible.
  • Same class in the same package     --> Private is Visible.
2. Package Scope
  • Within the same package -- > Private is Not Visible. 
  • Outside the package        ---> Private is Not Visible. 
Private with constructor 

To make a constructor as private we have to use private keyword before the constructor. Declaring super-class constructor as private will restrict to create an object of super-class in sub-class as private members are not accessible outside its scope. For ex-

public class prog{

private prog(){}

}

class A extends prog {

public static void main(String arg[]){

prog p= new prog(); //Cannot create object as constructor
is declared as private.

}
}

Private with variable

Like private constructor , variable can be declared as private and cannot be accessible in sub-class or any other class expect in the class in which it is declared as private. For ex-

public class prog{

private int x=10;
}

class A extends prog {

public static void main(String arg[]){

prog p= new prog();
System.out.println(x); //not visible as x is declare
as private.
}
}

Private with methods

Using private keyword before the name of the constructor makes it a private method and has accessibility limit to that class only and hence accessioning outside the class will give compilation error. For ex-

public class prog{

private void display(){}

}

class A extends prog {

public static void main(String arg[]){

prog p= new prog();
p.display(); //Compilation error as display()is private.
}
}


Available link for download