java – 为什么你不能在本地类中声明成员接口?

你不能在下面的块中声明一个接口

public void greetInEnglish() {

        interface HelloThere {
           public void greet();
        }

        class EnglishHelloThere implements HelloThere {
            public void greet() {
                System.out.println("Hello " + name);
            }
        }

        HelloThere myGreeting = new EnglishHelloThere();
        myGreeting.greet();
}

This Oracle tutorial 中,我得到了“你不能在本地类中声明成员接口.”因为“接口本质上是静态的”.

我是eagar用更合理的信息来理解这一点,为什么以及界面本身是如何静态的?

为什么上面的代码没有意义?

在此先感谢elloborate!

最佳答案

I am eagar to understand this with more rational information, why and
how interface are inherently static?

因为接口是隐式静态的,并且您不能在内部类中使用非最终静态.

Why are they implicitly static?

因为这就是他们设计它的方式.

and why above code does not make sense?

由于上述原因,

现在让我们简单一点:

静态意味着什么 – “与特定实例无关”.因此,假设类Foo的静态字段是一个不属于任何Foo实例的字段,而是属于Foo类本身.

现在想想接口是什么 – 它是一个契约,一个实现它的类承诺提供的方法列表.另一种思考方式是接口是一组“与特定类无关”的方法 – 任何类都可以实现它,只要它提供这些方法即可.

因此,如果一个接口与任何特定的类没有关系,那么很明显一个接口与一个类的实例无关 – 对吧?

我还建议你学习Why static can’t be local in Java?

点赞