Zack Zatkin-Gold
Zack Zatkin-Gold

Reputation: 824

Can you set class variables in the constructor method parameters?

Is it possible to set class variables by simply instantiating the class with parameters for the constructor function?

Psuedo code

public class Employee {
    String first_name;
    String last_name; // can this be set automatically from the parameter of the constructor function without having to explicitly set it?

    public Employee (String firstName, String lastName) {
        first_name = firstName; // is there a way to avoid having to type this?
        last_name = lastName;
    }
}

Upvotes: 0

Views: 5289

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

Perhaps the closest you can get in Java as is is:

public static Employee createEmployee(
    final String firstName, final String lastName
) {
    return new Employee() {
        //  methods using firstName and lastName
    }
}

(where Employee is some relevant interface)

Shame really when you look at modern languages like Simula. ;)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502746

No, you have to set it explicitly.

However, many IDEs such as Eclipse allow you to write your field declarations and then autogenerate constructors which set them.

(Note: I would suggest that you make fields private, and also final where possible. Also, avoid underscores in identifiers.)

Upvotes: 2

Related Questions