Note: Object Can Be Created With in The Same Class If It Has A Private Constructor
Note: Object Can Be Created With in The Same Class If It Has A Private Constructor
→ protected
→ default
→ private
------------------------------------------------------------------------------------------------------------------------
Question : Describe the accessibility level of each access modifier ?
→ public : have the highest visibility
→ protected : have higher visibility than default
→ default : have lower visibility than protected
→ private : have the lowest visibility
------------------------------------------------------------------------------------------------------------------------
Private Access Modifier :
→ We can’t declare a class as private. Until unless it is an inner class [nested class]
→ Private variables and methods must be accessed within the same class,
class Father {
private double accBal = 9999.00;
private void smoke(){
System.out.println("I am a chain smoker, my son should not know..");
}
public static void main(String[] args) {
Father f = new Father();
System.out.println(f.accBal);
f.smoke();
}
}
→ Private variables and methods can’t be accessed outside the class.
Example :
public class Son extends Father{
public static void main(String[] args) {
Father f = new Father();
//Private members can't be accessed outside the class
f.accBal;//CE
f.smoke();//CE
}
}
→ Private constructor can’t be accessed outside the class.
→ If we want to stop someone to create an object of a class, declare the constructor as
private.
[Note : Object can be created with in the same class if it has a private constructor]
Program Example :
class Father {