Why doesn't Java allow private members in interface?

后端 未结 13 1340
时光取名叫无心
时光取名叫无心 2020-12-07 13:11

Why doesn\'t Java allow private members in interface? Is there any particular reason?

13条回答
  •  时光取名叫无心
    2020-12-07 13:26

    There would be no way to implement such an interface. An answer to a question I posed strongly suggests that it would be impossible (without radically changing the rules) to implement an interface with private methods - this leaves open the question of why protected and package private methods are not allowed.

    class OuterClass
    {
         void run ( MyInterface x )
         {
               x . publicMethod ( ) ;  // why not?
               x . protectedMethod ( ) ; // why not?
               x . packagePrivateMethod ( ) ; // why not?
               x . privateMethod ( ) ; // why not?
         }
    
         interface MyInterface
         {
               public abstract void publicMethod ( ) ; // OK
    
               protected abstract void protectedMethod ( ) ; // why not?
    
               abstract void packagePrivateMethod ( ) ; // in interface default is public, but why not package private
    
               private void privateMethod ( ) ; // impossible to implement
         }
    
         class MyImpl implements MyInterface
         {
               public void publicMethod ( ) { } // ok
    
               protected void protectedMethod ( ) { } // no sweat
    
               void packagePrivateMethod ( ) { } // no sweat
    
               private void privateMethod ( ) { } // not happening
         }
    }
    

    The below code should achieve the desired result. Even though all methods are public, only public method is effectively public. protected method is effectively protected. packagePrivateMethod is effectively packagePrivate. privateMethod is effectively private.

    class WorkAround
    {
         void run ( MyPrivateInterface x )
         {
               x . publicMethod ( ) ;  
               x . protectedMethod ( ) ; 
               x . packagePrivateMethod ( ) ; 
               x . privateMethod ( ) ; 
         }
    
         public interface MyPublicInterface { void publicMethod ( ) ; }
    
         protected interface MyProtectedInterface extends MyPublicInterface { void protectedMethod ( ) ; }
    
         interface MyPackagePrivateInterface extends MyProtectedInterface { void packagePrivateMethod ( ) ; }
    
         private interface MyPrivateInterface extends MyPackagePrivateInterface { void privateMethod ( ) ; }
    }
    

提交回复
热议问题