5

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!

DigitalZebra
  • 39,494
  • 39
  • 114
  • 146

2 Answers2

8

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

Community
  • 1
  • 1
Richard Cook
  • 32,523
  • 5
  • 46
  • 71
2

This is how I would emulate it in Java.

public static Foo CONSTANT;

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

Using a static block will do what you need.

Or you could simply do:

public static Foo CONSTANT = new Foo("some", "arguments", false, 0);
jjnguy
  • 136,852
  • 53
  • 295
  • 323