Java equivalent of following read-only static code?

So, in C #, one of my favorite things is to do the following:

public class Foo { public static readonly Bar1 = new Foo() { SomeProperty = 5, AnotherProperty = 7 }; public int SomeProperty { get; set; } public int AnotherProperty { get; set; } } 

How do I write this in Java? I think I can make a static final field, however I'm not sure how to write the initialization code. Would Enums be the best choice in Java land?

Thanks!

+4
source share
2 answers

Java does not have equivalent syntax for C # object initializers, so you will need to do something like:

 public class Foo { public static final Foo Bar1 = new Foo(5, 7); public Foo(int someProperty, int anotherProperty) { this.someProperty = someProperty; this.anotherProperty = anotherProperty; } public int someProperty; public int anotherProperty; } 

As for the second part of the question about transfers: it is impossible to say without knowing what the purpose of your code is.

The following section discusses various approaches to modeling named parameters in Java: A named named parameter in Java

+5
source

This is how I will emulate it in Java.

 public static Foo CONSTANT; static { CONSTANT = new Foo("some", "arguments", false, 0); // you can set CONSTANT properties here CONSTANT.x = y; } 

Using a static block will do what you need.

Or you could just do:

 public static Foo CONSTANT = new Foo("some", "arguments", false, 0); 
+2
source

All Articles