The following code snippet shows that an interface in Java can have only one modifier which is public. No other modifiers (private and protected) are allowed within an interface neither with fields nor with any methods. Obviously among modifiers, private has no meaning to use within an interface but protected should be allowed within an interface because it can be incorporated by it's implementing class.
interface Demo
{
private final static int a=10; //Will not be compiled.
protected final static int b=20; //Will not be compiled.
public final static int x=0; //ok
abstract public void showSum();
}
while an abstract class is allowed to have all the modifiers private, public and protected. My question is only that a protected modifier is not allowed within an interface that somewhat seems to be allowed. Why?
解决方案
Obviously the best answer is "because that's how they defined it." I don't think I'd look too hard at the rationale behind decisions made when Java was initially defined; it was a long time ago, now, and experience gained by using the language has shown that many of those initial decisions were flawed.
In this case, an interface is intended to serve as a public protocol for communicating with an object, and as such, it was decided that all members must be public. This may not have been the best or most useful definition, but it's the one we have, and we have to live with it.