java接口的修饰符可以为,Java接口中只能有一个公共修饰符。为什么其余的不允许?...

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值