Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of the following static readonly C# code?

Tags:

java

.net

static

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!

like image 258
Polaris878 Avatar asked Feb 27 '23 04:02

Polaris878


1 Answers

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

like image 94
Richard Cook Avatar answered Mar 08 '23 13:03

Richard Cook