tags:

views:

58

answers:

2

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!

+2  A: 

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: http://stackoverflow.com/questions/1988016/named-parameter-idiom-in-java

Richard Cook
+1  A: 

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