登录  /  注册
Java的接口中中添加内部类,甚至实现外围接口的内部类,意义是什么?
高洛峰
高洛峰 2016-10-26 16:29:58
[Java讨论组]

比如《Thinking in Java》英文第4版p366页中的示例,现给出一个类似的例子:

interface IFoo { // 接口
    void how(String todo); // 方法签名
    class CFoo implements IFoo { //接口的内部实现
        public void how(String todo) {
            System.out.println("how to do: " + todo);
        }
    }
    class CBar { // 接口的内部类
        void where(String w) {
            System.out.println("where to: "+w);
        }
    }
}

// Driver
public class TestInterfaceWithClass {
    public static void main(String[] args) {
        IFoo iF = new IFoo.CFoo();
        iF.how("say love");
        IFoo.CBar bar = new IFoo.CBar();
        bar.where("Beijing");
    }
}

我的疑问:

书中说:"Normally, you can't put any code inside an interface, but a nested class can be part of an interface. Any class you put inside an interface is automatically public and static.Since the class is static, it doesn't violate the rules for interfaces--the nested class is only placed inside the namespace of the interface."

这段话有几点因果关系不是很明确:

You can't put any code inside an interface, but a nested class can be part of an interface. 
为什么嵌套类(包括single class: class c {}, implemented class: class CI implements IFoo { void how(String s) { //TODO } })可以在接口里存在? 既然interface内不能存在任何"method body"(比如 void f();), 那为什么可以存在class?, 这样的话, 接口原本存在的意义是不是被打乱了, 接口内部和具体类之间是不是有什么深层次的联系,能否从bytecode角度给予一些具体的说明?

Since the class is static, it doesn't violate the rules for interfaces. 
为什么内部class是static时就不会违反interface的规则? 这里的rules指的是什么? 是java语言规范里规定可以这么写,还是一种hack?


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号