Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Object { } Construct

Tags:

In Java, the standard way to create an object is using

MyClass name = new MyClass(); 

I also often see the construct

new MyClass() { /*stuff goes in here*/ }; 

I've been looking online for a while and can't find a good explanation of what the second construct style does or how it does it.

Can someone please explain how and why you would use the second construct?

like image 659
andrewheins Avatar asked Sep 10 '10 21:09

andrewheins


People also ask

What is construct object?

The Object constructor turns the input into an object. Its behavior depends on the input's type. If the value is null or undefined , it will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

Can we create new constructor object?

When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.

Is new A constructor?

Constructor functions or, briefly, constructors, are regular functions, but there's a common agreement to name them with capital letter first. Constructor functions should only be called using new .

How do you define a new object?

Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.


1 Answers

This construct makes actually two things: 1) It declares an anonymous class which extends the class you use in the constructor and 2) creates an instance of this anonymous class.

Edit: When using such a construct you can observe the anonymous class by looking at the generated .class files. There is the normal MyClass.class file and another one for each anonymous subclass: MyClass$1.class for the first and so on.

like image 164
ZeissS Avatar answered Jan 04 '23 07:01

ZeissS