开发者

What does new Object { } do?

开发者 https://www.devze.com 2023-04-12 04:40 出处:网络
I开发者_高级运维t 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.

I开发者_高级运维t 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?


This is called an anonymous class. Basically, you're defining a subclass in-place.

This call:

Object a = new Object() {
   // stuff
};

.. defines a new subclass of Object with //stuff in it (just like declaring that in a normal A 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:

interface Function {
    void run();
}

static void example(Function f) {
    f.run();
}

void runExample() {
    final int a = 10;
    example(new Function() {
        void run() {
            // Notice that "a" was defined in the outer scope
            System.out.println(a);
        }
    });
}


new Object() {
    //code here
}

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.


new Object() {
    //code here
}

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.

Object ob=new Object(){
    //code
}

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号