Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce visibility when implementing interface in Java

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 interface implemented in class A as private (reducing visibility in class A). I have to do this for security reason, how can I do this, is there a workaround. We do know that by default, the interface has public members. But there is no option for me, can someone help me. Thanks in advance.

-- So , there is no way, to have a class implement method from interface and make it private. And all classes that implement any interface's method will always have public methods?

like image 555
David Prun Avatar asked Jul 05 '11 19:07

David Prun


2 Answers

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?

like image 183
highlycaffeinated Avatar answered Nov 08 '22 10:11

highlycaffeinated


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.

like image 32
Jon Skeet Avatar answered Nov 08 '22 09:11

Jon Skeet