new Object { } 的作用是什么?
很难搜索这方面的信息,因为我不知道它叫什么,所以我想这是我的第一个问题。
使用此表示法是否:
new Object() {//code here}
创建一个 Object 类型的新对象或创建一个作为 object 子类的新对象?如果它是一个子类,您可以将用于声明类的所有内容(成员变量、函数、内部类)放在大括号内吗?你甚至可以为它编写一个构造函数吗?
It was difficult to search for information on this because I don't know what it's called, so that's my first question I guess.
Does the use of this notation:
new Object() {//code here}
create a new object of type Object or create a new object that is a subclass of object? If it is a subclass, can you put everything you could use to declare a class (member variables, functions, inner classes), inside the braces? Could you even write a constructor for it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这称为匿名类。基本上,您正在就地定义一个子类。
这个调用:
.. 定义了一个新的 Object 子类,其中包含
//stuff
(就像在普通的A extends Object
中声明它一样。维基百科有 一篇关于它们的好文章。
它们主要用于闭包,这意味着匿名类中定义的函数可以访问封闭范围内的
final
变量:
This is called an anonymous class. Basically, you're defining a subclass in-place.
This call:
.. defines a new subclass of Object with
//stuff
in it (just like declaring that in a normalA extends Object
.Wikipedia has a good article about them too.
They're useful primarily for closures, which means that the functions defined in your anonymous class have access to
final
variables from the enclosing scope.Example-ish:
将创建一个扩展
Object
的新匿名内部类。这是一个完全有效的类,可以包含普通非匿名类所包含的任何内容。尽管在匿名类中声明新方法是非常不切实际的,因为它们的范围非常小。Would create a new anonymous inner class which extends
Object
. This is a completely valid class and may contain anything that a normal non-anonymous class contains. Though it would be quite impractical to declare new methods inside an anonymous class since they would have a very small scope.这是有效的。它将创建扩展 Object 的匿名内部类。但您将无法保存其参考。您可以使用的引用仅属于对象类。
通过使用此引用,您只能访问 Object 类的方法。在此匿名类中声明的任何新方法都不会被访问。绝对可以使用重写方法。所以创建其他方法是没有用的,因为你永远无法使用。另外,在这个类中你不能创建构造函数,因为这是扩展Object的匿名类,并且构造函数只能用类名创建,而你不知道类名。
It is valid. It will create Anonymous inner class which extends Object. But you will not be able to save its reference. The Reference you can use is of Object class only.
By using this reference you can only access the methods of Object class. Any new methods declared in this anonymous class will not get accessed. Definitely overridden methods can be used. So there is no use of creating other methods as you can never use. Also in this class you can't create a constructor, as this is anonymous class which extends Object,and constructor can only be created with class name,and you don't know the class name.