用于实例化内部类的奇怪语法 [英] Strange syntax for instantiating an inner class

查看:210
本文介绍了用于实例化内部类的奇怪语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没想到在这个阶段我会在Java中遇到根本上新的语法,但是我只是遇到了一些问题:



确切的上下文和下面的代码应该做什么是非常不相关的 - 它只是为了给某种上下文。



我试图合成创建一个事件在IT Mill工具包,所以我写了这样的行:

  buttonClick(new Button.ClickEvent(button)); 

但是,Eclipse给了我以下错误信息:


没有可以访问类型为Button的封闭实例。必须使用Button类型的封闭实例(egxnew A(),其中x是Button的实例)限定分配。


我重写上面的行如下,它不会抱怨:

  buttonClick(button.new ClickEvent(button)); // button instanceof Button 

所以,我的问题是:后面的语法是什么意思, 什么是Java抱怨,它在第二个版本中做了什么?



背景info: Button Button.ClickEvent 都是非抽象公开类。

b $ b

解决方案

内部类(如 Button.ClickEvent )需要引用外部实例该语法创建一个 Button.ClickEvent

的新实例

/ code>其外部类引用设置为按钮的值。



忽略缺少封装等,它只是为了演示的目的:

  class Outer 
{
字符串名称;

class Inner
{
void sayHi()
{
System.out.println(Outer name =+ name);
}
}
}

public class Test
{
public static void main(String [] args)
{
Outer outer = new Outer();
outer.name =Fred;

Outer.Inner inner = outer.new Inner();
inner.sayHi();
}
}

请参阅规范的第8.1.3节有关内部类和封闭实例的更多信息。


I didn't imagine that I would encounter radically new syntax in Java anymore at this stage, but lo and behold, I just encountered something:

The exact context and what the code below should do is pretty irrelevant - it's there just to give some kind of context.

I'm trying to synthetically create an event in IT Mill Toolkit, so I wrote this kind of line:

buttonClick(new Button.ClickEvent(button));

But, Eclipse gives me the following error message:

No enclosing instance of type Button is accessible. Must qualify the allocation with an enclosing instance of type Button (e.g. x.new A() where x is an instance of Button).

When I rewrite the line above as follows, it doesn't complain anymore:

buttonClick(button.new ClickEvent(button)); // button instanceof Button

So, my question is: What does the latter syntax mean, exactly, and why doesn't the first snippet work? What is Java complaining about, and what's it doing in the second version?

Background info: Both Button and Button.ClickEvent are non-abstract public classes.

解决方案

Inner classes (like Button.ClickEvent) need a reference to an instance of the outer class (Button).

That syntax creates a new instance of Button.ClickEvent with its outer class reference set to the value of button.

Here's an example - ignore the lack of encapsulation etc, it's just for the purposes of demonstration:

class Outer
{
    String name;

    class Inner
    {
        void sayHi()
        {
            System.out.println("Outer name = " + name);
        }
    }
}

public class Test
{
    public static void main(String[] args)
    {
        Outer outer = new Outer();
        outer.name = "Fred";

        Outer.Inner inner = outer.new Inner();
        inner.sayHi();
    }
}

See section 8.1.3 of the spec for more about inner classes and enclosing instances.

这篇关于用于实例化内部类的奇怪语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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