Java - 内联类定义 [英] Java - inline class definition

查看:96
本文介绍了Java - 内联类定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中看到过几个类似的例子,我希望有人可以解释发生了什么。看起来像一个新类可以内联定义,这对我来说似乎很奇怪。第一个打印输出行是预期的,因为它只是toString。然而第二个看起来像函数可以重写内联。这有技术术语吗?或者任何更深入的文档?谢谢!

I've seen a couple of examples similar to this in Java, and am hoping someone can explain what is happening. It seems like a new class can be defined inline, which seems really weird to me. The first printout line is expected, since it is simply the toString. However the 2nd seems like the function can be overriden inline. Is there a technical term for this? Or any documentation which goes into more depth? Thanks!

如果我有以下代码:

public class Apple {
    public String toString() {
        return "original apple";
    }
}

public class Driver {
    public static void main(String[] args) {
        System.out.println("first: " + new Apple());
        System.out.println("second: " + 
            new Apple() {
                public String toString() {
                    return "modified apple";
                }
            }
        );
    }
}

代码输出:

first: original apple
second: modified apple


推荐答案

这是一个匿名的内部类。您可以在Java文档链接中找到有关它的更多信息,以获取内部类 编辑 我正在添加更好的链接描述匿名内部类,因为Java文档留下了一些需要的东西。 / EDIT

It is an anonymous inner class. You can find some more information about it at the Java documentation link for Inner Classes. EDIT I am adding a better link describing anonymous inner classes, as the Java documentation leaves something to be desired. /EDIT

大多数人都会使用匿名内部类来动态定义侦听器。考虑这种情况:

Most people will use Anonymous inner classes to define listeners on the fly. Consider this scenario:

我有一个按钮,当我点击它时我想让它显示一些内容安慰。但我不想在不同的文件中创建一个新类,我不想在此文件中稍后定义内部类,我希望逻辑立即可用。

I have a Button, and when I click it I want it to display something to the console. But I do not want to have to create a new class in a different file, and I don't want to have to define an inner class later in this file, I want the logic to be immediately available right here.

class Example {
    Button button = new SomeButton();

    public void example() {
        button.setOnClickListener(new OnClickListener() {
            public void onClick(SomeClickEvent clickEvent) {
                System.out.println("A click happened at " + clickEvent.getClickTime());
            }
        });
    }

    interface OnClickListener {
        void onClick(SomeClickEvent clickEvent);
    }

    interface Button {
        void setOnClickListener(OnClickListener ocl);
    }
}

这个例子有点人为,显然不完整,但是我认为它可以解决这个问题。

The example is somewhat contrived and obviously not complete, but I think it gets the idea across.

这篇关于Java - 内联类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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