CaptainTreibholz CaptainTreibholz - 4 months ago 8
Java Question

Create instance of a class and set variables

in C# you can create a instance of a class and set the values of variables at the same time:

public class Object
{
public virtual long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Version { get; set; }
public long ParentId { get; set; }
}

public class Start
{
Object object= new Object()
{
Id = 1,
Name = name,
ParentId = parentId,
Description = null,
Version= 2
};
}


Is this possible in Java aswell and how?

Answer

The standard way for setting values when creating an instance is to just have a constructor:

class ExampleObject {
    long id;
    String name;
    String description;
    int version;
    long parentId;

    public ExampleObject(final long id, final String name, final String description, final int version, final long parentId) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.version = version;
        this.parentId = parentId;
    }
}

And then call it like:

ExampleObject exampleObject = new ExampleObject(1, name, null, 2, parentId);

It is possible to use a similar syntax to what you have shown, but it has quite a few downsides which you should research about before using it (and you also cannot use variables with this):

ExampleObject exampleObject = new ExampleObject() {{
    id = 1;
    name = "";
    parentId = 2;
    description = null;
    version = 2;
}};


class ExampleObject {
    long id;
    String name;
    String description;
    int version;
    long parentId;
}

What this does is creates an anonymous class with a static initialiser block. A static initialiser block looks like:

class ExampleObject {
    long id;
    String name;
    String description;
    int version;
    long parentId;

    {
        id = 1;
        name = "";
        parentId = 2;
        description = null;
        version = 2;
    }
}
Comments