An interface in Java can have one and only one modifier which is public. Why are the rest not allowed? [duplicate]

拥有回忆 提交于 2019-12-12 21:32:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!