-1

I'm trying to understand the initialization of the object property directly but getting a compilation error.

In C#, the below code works:

new Employee() {
  Name = "John"
}

In Java, can one please tell me the equivalent of the same, as the below piece of code throws compilation error:

new Employee() {
  Name = "John"
} // Throws error in Java

public class Employee {
  public string Name;
}

I don't want to use the constructor to initialize the object, just for my understanding of the Java syntax. Please let me know if there is a way to initialize the object in Java as in C# like:

new Employee() {
  Name = "John"
}
Aryan M
  • 571
  • 3
  • 12
  • 33

3 Answers3

1

The Java equivalent is for the class to provide suitable constructors.

new Employee("John");

That some other language does it some other way doesn't change that.

Alternatively, if the class is so implemented, you may write:

new Employee().setName("John");

...though that seems needlessly clunky and also admits the existence of nameless Employees.

Setters like that would look like:

Employee setXyz(String xyz) {
    this.xyz = xyz;
    return this;
}

...so you can chain them together. But this approach is only better when there are comparatively many things that can optionally be set, and I would not recommend it for values that are required to be set, like the name of an Employee.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
something
  • 174
  • 4
0

If you don't want to use constructor, you can do it by one of these way:

public class Employee {
    public String Name;

    public static void main(String[] args) {
        new Employee().Name = "John";
        // or
        Employee employee = new Employee();
        employee.Name = "John";
        // or
        Employee employee2 = new Employee();
        employee2.setName("John");

    }

    public void setName(String name) {
        Name = name;
    }
}
0

There is also another way, although I strongly do not recommend it (as do some of the answers in the linked question): double brace initialization

    static class Employee {
        String name;
    }

    @Test
    public void doubleBraceInit() {
        Employee john = new Employee() {{
            name = "John";
        }};

        assertEquals(john.name, "John");
    }

However: You are much better off using things like a) a good constructor, b) the builder pattern, or c) setters.

sfiss
  • 2,119
  • 13
  • 19