Java 问题,来自 C++程序员
我正在学习 Java,现在我已经克服了包的难题,一切进展顺利。我可以将我正在学习的大多数事物与我至少已经了解其概念的事物联系起来。但是下面这段代码到底是怎么回事呢?它是某种形式的构造函数,还是匿名对象?
Something obj = new Something()
{
private static final int num = 3;
public void meth()
{
// w/e
}
};
I'm learning Java, and now that I'm over the packages hump, things are going smoothly. I can draw similarities between most things I'm learning with things I already know at least the concept of. But what on earth is going on with the following bit of code? Is it some form of constructor, or anonymous object?
Something obj = new Something()
{
private static final int num = 3;
public void meth()
{
// w/e
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你明白了 - 这会创建一个
Something
的匿名内部类。另请参阅:嵌套类(Java 教程) 和 匿名类。
You got it - this creates an anonymous inner class of
Something
.See also: Nested Classes (The Java Tutorial) and Anonymous Classes.
现在,当我实际定义按钮时,我会这样做。通过提供它所需的一条线路,这是它与其他线路不同的唯一原因。现在我可以为每个文件创建一个新文件,并为每个文件定义一个新类。这个就简单多了。
现在,当我处理按下的按钮时,请记住 TopButton 的定义...
我们知道
triggerEvent()
最终会被定义。我们可以在每个按钮的基础上定义它,当单击面板时,无论我们定义什么triggerEvent()
,它都会被调用。Now, when I actually define my buttons, I do this. By providing the one line it needs, the only thing that makes it different from others. Now I could make a new file for each one, and define a new class for each one. This is much simpler.
Now, when I handle the buttons being pressed, remember back in the definition of TopButton... there was
We know
triggerEvent()
eventually gets defined. We can define it on a per-button basis, and when the panel gets clicked, no matter what we definedtriggerEvent()
to be, it gets called.这样的构造创建了执行该构造的类的匿名内部类,并且派生自 Something (不是 Something 的内部类)。
这个想法是快速提供抽象类、接口的实现,或重写类的某些功能。
(new Thread(){ public void run() { System.out.println("在另一个线程上执行"); }}).start();
Such construct creates an anonymous inner class of a class where this construct is executed, and derived from Something (not an inner class of Something).
The idea is to quickly provide implementations for abstract classes, interfaces, or override some functionality of a class.
(new Thread(){ public void run() { System.out.println("executed on another thread"); }}).start();