问题
Possible Duplicate:
Protected in Interfaces
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?
回答1:
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.
回答2:
All methods and fields in an interface
should be declared in such a way so that they can be invoked from anywhere. Not only from within a subclass.
Only public
modifier can make this happen.
However, it should be avoided to have a field in interface. if possible.
回答3:
An abstract class provides some implementation that subclasses inherit.
An interface simply defines an external API without providing any implementation. The whole idea behind an interface is that the implementation is left entirely to the implementing class.
来源:https://stackoverflow.com/questions/8027394/an-interface-in-java-can-have-one-and-only-one-modifier-which-is-public-why-are