比如《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?
Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
语法规定。jdk本身就没有限制class不能存在于interface中啊
interface无法创建实例,如果内部class是非静态的那永远也无法使用,所以必须得是静态内部类,这就像在interface中定义的变量全部都是public static一个概念。