Reputation: 824
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
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
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