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.
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:
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.