Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there object creation expressions in Java, similar to the ones in C#?

In C#, I can create an instance of every custom class that I write, and pass values for its members, like this:

public class MyClass
{
    public int number;
    public string text;
}

var newInstance = new MyClass { number = 1, text = "some text" };

This way of creating objects is called object creation expressions. Is there a way I can do the same in Java? I want to pass values for arbitrary public members of a class.

like image 482
Slavo Avatar asked Jun 29 '11 08:06

Slavo


People also ask

How objects can be created in Java?

Using the new keyword in java is the most basic way to create an object. This is the most common way to create an object in java. Almost 99% of objects are created in this way. By using this method we can call any constructor we want to call (no argument or parameterized constructors).

Which is the keyword that is used to create an object in the Java program?

Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

Can we create object inside class in Java?

All methods must be encapsulated within a class. Therefore the main method as an entry point to the program must be within a class. When you run this program the main method will be run once and will execute the code inside it. In your case it creates an object of the enclosing class TestClass .

Can we create object without constructor in Java?

Actually, yes, it is possible to bypass the constructor when you instantiate an object, if you use objenesis to instantiate the object for you. It does bytecode manipulations to achieve this. Deserializing an object will also bypass the constructor.


1 Answers

No, there's nothing directly similar. The closest you can come in Java (without writing a builder class etc) is to use an anonymous inner class and initializer block, which is horrible but works:

MyClass foo = new MyClass()
{{
    number = 1;
    text = "some text";
}};

Note the double braces... one to indicate "this is the contents of the anonymous inner class" and one to indicate the initializer block. I wouldn't recommend this style, personally.

like image 66
Jon Skeet Avatar answered Sep 24 '22 02:09

Jon Skeet