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?
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.
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).
The minimum time to see results from Can-C eye drops, which is generally twice per day, is 6 months.
(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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With