So, in C# one of my favorite things to do is 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 would I write this in Java? I'm thinking I can do a static final field, however I'm not sure how to write the initialization code. Would Enums be a better choice in Java land?
Thanks!
Java does not have equivalent syntax to C# object initializers so you'd have 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 question regarding enums: that's impossible to say without knowing what the purpose of your code is.
The following thread discusses various approaches to simulating named parameters in Java: Named Parameter idiom in Java
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