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. You can only bet during designated occasions, usually indicated by timers or lights. Bet https://casino.edu.kg/%EC%A0%95%EC%B9%B4%EC%A7%80%EB%85%B8.html limits differ relying on what you are be} wagering on; for roulette, a ‘straight up’ has a lower restrict than an odd/even bet as they pay out is larger. 300 Spins credited immediately upon qualifying deposit on pre-selected sport. The Hanover Sports & Social will be the third of the branded venues to supply sports activities gaming, together with places that opened late last 12 months and this 12 months in Pittsburgh and Philadelphia.

    ReplyDelete

Post a Comment