为什么静态上下文中的匿名类有效 [英] Why is an anonymous class in a static context valid

查看:160
本文介绍了为什么静态上下文中的匿名类有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的匿名类有什么误解。请考虑以下简单示例:

I have a misunderstanding about what an anonymous class in Java is. Consider the following simple example:

public static void main (String[] args) throws java.lang.Exception
{
    B b = new B(){ };
    System.out.println(b.b);
}

interface B{ int b = 1; }

DEMO

DEMO

为什么代码会编译? JLS,chapt 15 说:

Why does the code compile? The JLS, chapt 15 says:


匿名类始终是内部类(第8.1.3节);它绝不是
static

An anonymous class is always an inner class (§8.1.3); it is never static

JLS,第8章


内部类是一个嵌套类,它没有显式或隐式
声明为static。

An inner class is a nested class that is not explicitly or implicitly declared static.

所以匿名类是一个内部类。但我们在静态环境中使用它们。为什么在这里是正确的?

So the anonymous class is an inner class. But we use them in the static context. Why is it correct here?

推荐答案

可以在静态上下文中创建一个类,而不是声明为静态,这就是发生在这里。让我们看一下被声明为静态的东西,并在静态上下文中创建意味着:

A class can be created in a static context without being declared static, and this is what is happening here. Let's look at what being declared static, and created in a static context means:

在静态上下文中创建的匿名类与非静态上下文之间的区别在于它有一个封闭的实例:

The difference between an anonymous class created in a static context and a non-static context is whether it has an enclosing instance:


如果C是一个匿名类,那么:

If C is an anonymous class, then:


  • 如果类实例创建表达式出现在静态上下文中,那么我没有立即封闭的实例。

  • If the class instance creation expression occurs in a static context, then i has no immediately enclosing instance.

否则,i的直接封闭实例就是这个。

Otherwise, the immediately enclosing instance of i is this.

一个嵌套类声明static允许静态成员:

A nested class that is declared static allows static members:


内部类是未显式或隐式声明为静态的嵌套类。

An inner class is a nested class that is not explicitly or implicitly declared static.

根据Java编程
语言的通常规则,不是内部类的嵌套类可以自由地声明静态成员

A nested class that is not an inner class may declare static members freely, in accordance with the usual rules of the Java programming language.

通过说一个隐含声明为静态的嵌套类,它引用了接口中的类:

By saying a nested class that is 'implicity declared static', it refers to things like classes within interfaces:


接口的成员类是隐式静态的(§9.5)所以绝不会将
视为内部类。

A member class of an interface is implicitly static (§9.5) so is never considered to be an inner class.

匿名类不是静态的(既不是显式的关键字,也不是隐式的,比如在接口内),因此不允许声明静态成员。但是它们可以在静态上下文中创建,这意味着它们不会引用封闭的实例。

Anonymous classes are not declared static (neither explicitly with a keyword, or implicitly such as being inside an interface), and so do not allow the declaration of static members. They can however be created within a static context, which means that they don't refer to an enclosing instance.

因为匿名类未声明为静态,所以两者都引用问题是一致的。

Because the anonymous classes are not declared static, both quotes in the question are consistent.

这篇关于为什么静态上下文中的匿名类有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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