嵌套在类中的接口可以是非静态的吗? [英] Can an interface nested inside a class be non-static?

查看:54
本文介绍了嵌套在类中的接口可以是非静态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在在线阅读有关Java中的嵌套接口的一些文章[1] [2],我明白这一点

I'm reading about some articles[1][2] online about nested interface in Java, I understand that

interface A {
    ...
    interface B { // this is static by default
        ...
    }
}

但是我不确定

class C {
    ...
    interface D { // Is this static by default? Why?
        ...
    }
}

简而言之,嵌套接口始终是静态的"是真的吗?

In short, is that "a nested interface is always static" true?

[1] https://beginnersbook.com/2016/03/nested-or-inner-interfaces-in-java/
[2] https://www.programcreek.com/2013/08/inner-interface-in-java/

推荐答案

非静态内部类只是语法糖.非静态内部类与标准外部"类完全相同,但有一个例外:它具有外部类类型的不可见字段,并声明为 final .内部类的所有构造函数都必须将要设置该字段的外部实例作为第一个参数..然后,遍历所有语法糖袋以隐藏它们.

a non-static inner class is just syntax sugar. A non-static inner class is exactly the same as a standard 'outer' class, with one exception: It has an invisible field of the type of your outer class which is declared final. ALL constructors of your inner class have as first parameter the instance of the outer to which this field must be set.. and then there's a biiig sack of syntax sugar thrown all over this to also hide those.

但这确实是它的工作方式,您可以使用javap进行确认.因此,给定:

But that's really how it works, and you can use javap to confirm it. So, given:

public class Outer { public class Inner {} }

与之相对:

public class Outer {}
class Desugared {
    private final Outer outer;
    public Desugared(Outer outer) { this.outer = outer; }
}

除了语法外,这些都是相同的:

these things are the same except for syntax:

Outer o = new Outer();
o.new Outer.Inner();

与以下相同:

Outer o = new Outer();
new Desugared(o);

等.

这就是问题:接口没有字段.

鉴于他们没有,他们无法拥有此隐藏字段.因此,它们不能是非静态的".因此,它们是隐式的静态"(它们没有隐式可用的外部类实例),并且您无法更改它.

Given that they don't, they cannot have this hidden field. And therefore they cannot be 'non-static'. They are therefore implicitly 'static' (they do not have an instance of the outer class implicitly available to them), and you can't change that.

这篇关于嵌套在类中的接口可以是非静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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