Java中的接口只能有一个且只有一个公共修饰符.为什么其余的都不被允许? [英] An interface in Java can have one and only one modifier which is public. Why are the rest not allowed?

查看:244
本文介绍了Java中的接口只能有一个且只有一个公共修饰符.为什么其余的都不被允许?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
受接口保护

Possible Duplicate:
Protected in Interfaces

以下代码片段显示Java中的接口只能具有一个 public 修饰符.接口中不允许使用字段和任何方法的其他修饰符(私有修​​饰符和受保护修饰符).显然,在修饰符之间,private在接口内没有任何意义,但是应该允许在接口内使用protected,因为它可以由其实现类合并.

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();
}

同时允许抽象类将所有修饰符设为private,public和protected.我的问题是,在某种程度上似乎被允许的接口内,不允许不允许使用受保护的修饰符.为什么?

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?

推荐答案

显然,最好的答案是因为这就是他们的定义方式".我认为在最初定义Java时做出的决策背后的理由我不会太费劲.在很久以前,现在,使用这种语言获得的经验表明,许多最初的决定都是有缺陷的.

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.

这篇关于Java中的接口只能有一个且只有一个公共修饰符.为什么其余的都不被允许?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆