AWS networking

Role of Private and Protected Access Modifiers in Java Classes

Only Public or Default access modifiers can be applied to java classes and interfaces. Why can't we use private or protected?

private class test {} or  protected class test{} would give compile errors if test is a top level class.

Access to members permitted by each modifier.

Access Levels
ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN

Private means visible only to the enclosing class. In other words accessible only within the class. Because of these reasons there is no meaning when private applied to a top-level class. This is same for the interfaces as well. Private can be applied to nested classes and interfaces. Below are some examples.

Nested Class Example
class A{  
  private interface Message{  
   void msg();  
  }  

class B{  
  private class Message{  
   void msg(){}
  }  


Protected means visible to the enclosing class, its sub classes and the enclosing class's package. Sub class of the enclosing class may be in the same package as the enclosing class or a different one. Due to this visibility rules, there is no point of having protected access modifier in top level classes or interfaces. And also the Default modifier covers the "visible to the enclosing class's package" feature of Protected modifier. Using protected is meaningless and redundant.Protected can be applied to nested classes and interfaces.

Nested Class Example
class A{  
  protected interface Message{  
   void msg();  
  }  


class B{  
  protected class Message{  
   void msg(){}
  }  

A class or interface cannot be private or protected except nested class or nested interface. Only Public or Default access modifier can be applied for class and interface.
NOTE : A top level class is a class that is not a nested class.A nested class is any class whose declaration occurs within the body of another class or interface.
NOTE : Default access modifier means visible only within the package.

Comments

  1. I have checked your site and i have found some duplicate content, that's why you don't rank high in google, but
    there is a tool that can help you to create 100% unique articles,
    search for: Boorfe's tips unlimited content

    ReplyDelete

Post a Comment