Access Modifiers in Java

The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.
Java provides a number of access modifiers to help you set the levelof access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.
  1. public
  2. protected
  3. no-modifier(default)
  4. private
Public
  • It is applicable to a class, a method or a field.  
  • Public class, method or a variable are visible to all the classes defined in different package.
  •  A public class, method or field can be referenced from outside the class in which it is declared. 
Protected
  • It  is used as an access control modifier.
  • It is applicable to a class, a method or a field.  
  •  protected method or a variable is only visible to the classes within the same package.
  •  A protected  class, method or field are only referenced from within the class in which it is declared
Default
No modifer (declaring without an access modifer). Using ‘no modifier’ is also sometimes referred as 'package-private' or 'default' or 'friendly' access
  • The default access level is declared by not writing any access modifier at all.
  • Default access levels means that code inside the class itself + code inside classes in the same package as this class, can access the class, field, constructor or method.
  •  Therefore, the default access modifier is also sometimes called a package access modifier.
  • Subclasses cannot access methods and member variables in the superclass, if they have default accessibility declared, unless the subclass is located in the same package as the superclass.
Private
  • It is applicable to a class, a method or a field. 
  • private method or a variable is not visible outside a class or to its subclasses.
  • Variables that are declared private can be accessed outside the class if public getter methods are present in the class
  • A private (inner) class, method or field are only referenced from within the class in which it is declared. 
Access specify

Within class Same package sub class Same package non-sub class Different package non-sub class Different package sub class
Public valid valid valid valid valid
protected valid valid valid valid invalid
default valid valid valid invalid invalid
private valid invalid invalid invalid invalid

 



 

Latest Tutorial


Most Visited Tutorial