Reduce visibility when implementing interface in Java

后端 未结 4 1351
误落风尘
误落风尘 2021-01-11 18:12

I would like to design class A implements interface C and reduce the visibility of a method (declared in C)to make it secure from outer world, make one of the methods in in

相关标签:
4条回答
  • 2021-01-11 18:22

    No, you can't reduce the visibility of a method in an interface. What would you expect to happen if someone wrote:

    C foo = new A();
    foo.methodDeclaredPrivateInA();
    

    ? As far as the compiler is concerned, everything with a reference to an implementation of C has the right to call any methods within it - that's what Liskov's Substitution Principle is all about.

    If you don't want to implement the whole of a public interface, don't implement it - or throw exceptions if you absolutely must.

    It's also worth noting that the accessibility provided in source code is rarely a good security measure. If your class is running in a VM which in turn gets to determine its own permissions, anyone can make members visible via reflection.

    0 讨论(0)
  • 2021-01-11 18:22

    You can't reduce the visibility of the method of an interface in Java. Is it acceptable for you to implement the method by throwing a java.lang.UnsupportedOperationException?

    0 讨论(0)
  • 2021-01-11 18:23

    You cannot reduce visiblity because you could write something along the lines of

    C newC = new A();
    
    0 讨论(0)
  • 2021-01-11 18:27

    This approach worked for me. Any new function added to PrivateInterface would break still break PublicSampleClass

    private interface PrivateInterface {
        void fooBar();
    }
    
    public class PublicSampleClass {
    
        private final listenerInterface = new PrivateInterface {
             public void fooBar() {
                PublicSampleClass.this.fooBar();
             }
        };
    
        protected void fooBar() {
          // Non public implementation
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题