0

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;
    }
}
4
  • Yes. You can initialise class level variables in constructor. Commented Feb 2, 2012 at 23:06
  • No (at least, without reflection, which I believe is not an option here.) At best, you can provide default values in the field declaration (String first_name = "John";) but you need to somehow instruct the JVM how to assign the values to the fields (you might want to swap the ctor arguments, right?) Commented Feb 2, 2012 at 23:07
  • @RaviG: AFAIU, the question was to automatically copy the ctor argument values into the object fields (according to the comments in the code.) Commented Feb 2, 2012 at 23:09
  • Your constructor is not properly defined, it should be just public Employee not public function Employee. Commented Feb 2, 2012 at 23:11

2 Answers 2

2

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

then autogenerate constructors which set them. ... and then rearrange the parameters order [manually] :)
@bestsss: Well, Eclipse lets you order them manually before it generates the constructor, IIRC...
0

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. ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.