为什么静态上下文中的匿名类有效

为什么静态上下文中的匿名类有效

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

问题描述

限时删除!!

我对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

为什么代码会编译? 说:

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

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

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:


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

  • 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:

根据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:

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

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.

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

1403页,肝出来的..

09-06 10:19