Is there a shortcut for entering this.x = x in java when constructing an object?
When I store a parameter (or is it an argument?) For a variable of a private instance of a class, is there a faster way to write this.x = x
(where x is the argument to the constructor and this.x
is an instance variable)? Sometimes with longer variable names I find it a bit repetitive, is there something like x++;
, etc.?
I am new to Java so let me know if I can do something clearer.
source to share
No, not at all. I'm not sure what you mean by x++
- what the postfix increment operator is - but the only way to assign variables is by assigning them.
For example:
public class Student {
private String name;
private int age;
private double gradePointAverage;
public Student(String name, int age, double gradePointAverage) {
this.name = name;
this.age = age;
this.gradePointAverage = gradePointAverage;
}
}
Most IDEs will have a shortcut to automatically generate a constructor for you. For example, IntelliJ allows you to type alt + insert, which will show a context menu allowing you to automatically generate constructors, getters and setters.
source to share
Not. You can do this using an IDE to help you. Try Eclipse or IntelliJ IDEA .
Using the IDE you can Eclipse: Create Getters and Setters or IntelliJ: Create Getters and Setters
source to share
Generally speaking, there is no syntactic shorthand. However, there are ways to avoid the need for this. In particular, I'm a big fan auto/value
, a project that allows you to define values for types with a minimum boiler plate, for example:
@AutoValue
abstract static class Animal {
static Animal create(String name, int numberOfLegs) {
return new AutoValue_Animal(name, numberOfLegs);
}
abstract String name();
abstract int numberOfLegs();
}
Since auto/value
it does, this isn't a good solution for small programs that don't use Maven or Ant, but presumably for small projects you won't mind soft redundancy this.x = x;
.
source to share