Sunday, 17 April 2011

What are Access Specifiers available in Java?

Java offers four access specifiers, listed below in decreasing accessibility:
  • Public- public classes, methods, and fields can be accessed from everywhere.
  • Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
  • Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
  • Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.


 Situation   public   protected   default   private 
 Accessible to class
 from same package? 
yes yes yes no
 Accessible to class
 from different package? 
yes  no, unless it is a subclass  no no



No comments:

Post a Comment