Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C# style object initialization be used in Java?

In C# it's possible to write:

MyClass obj = new MyClass() {     field1 = "hello",     field2 = "world",     field3 = new MyOtherClass()     {         etc....     } } 

I can see that array initialization can be done in a similar way but can something similar to the above be done in Java too, and if so, what's the syntax?

like image 764
Chris Simpson Avatar asked Jul 12 '11 17:07

Chris Simpson


People also ask

Is Can-C good for dogs?

SAFE FOR HUMANS AND DOGS - Can-C is the first and only patented NAC eye drop that uses the exact formula proven effective in both animal and human trials, offering a non-invasive alternative to cataract surgery.

What are Can-C eye drops used for?

Can-C Eye Drops with N-acetylcarnosine help to soothe and rejuvenate tired eyes, help with macular degeneration, cataracts, and other age-related eye disorders. Can-C eye drops for cataracts contain lubricants, an antioxidant and an anti-glycating agent, N-Acetyl-Carnosine (NAC).

How long does Can-C eye drops take to work?

The minimum time to see results from Can-C eye drops, which is generally twice per day, is 6 months.

Can-C active ingredient?

(IVP)'s scientists developed the lubricant eye drops (Can-C) designed as 1% N-acetylcarnosine (NAC) prodrug of L-carnosine containing a mucoadhesive cellulose-based compound combined with corneal absorption promoters in a sustained drug delivery system.


2 Answers

That initialization syntax is not present in Java.

A similar approach is to use double brace initialization, where you create an anonymous inner sub class with an initializer block:

MyClass obj = new MyClass() {{   // in Java these would be more like this: setFieldX(value);   field1 = "hello";   field2 = "world";   field3 = new MyOtherClass() ... }}; 

Be aware though, that you're actually creating a subclass.

Another approach is to create a builder for MyClass, and have code like this:

MyClass obj = new MyClassBuilder().   withField1("hello").   withField2("world").   withField3(new MyOtherClass()).   build(); 
like image 132
Jordão Avatar answered Oct 18 '22 03:10

Jordão


Java does not have the capability built in to instantiate an object using the shorter syntax. The C# compiler handles this and separates out the property setters in the IL. Until the Java langauge devs decide this is important, you will not be able to take this shortcut.

like image 44
Gregory A Beamer Avatar answered Oct 18 '22 02:10

Gregory A Beamer