Question

With regards to object-oriented Java constructor syntax and design, specifically parameterized or specific constructors, it is the accepted process, as describe in books, to build a parameterized constructor in this form:

public Car (int x, int y, int g) {
   xdistance = x;
   ydistance = y;
   gas = g;

}

For shorthand and simplification, why can we not build the constructor in this form?

public Car (int xdistance, int ydistance, int gas) {
}

This is a cleaner approach, with less code, yet I do not see this syntax adopted in tutorials.

Was it helpful?

Solution

Java simply isn't defined that way. The parameter names in a constructor can be whatever you like, and they are entirely unrelated to the field names in the class.

You could propose a change to the Java language that allowed for that, but it is unlikely to be accepted in it's current form, because your proposed syntax will change the meaning of currently valid Java programs. Your example is valid Java, it takes three ints and does nothing with them.

OTHER TIPS

As others already said, Java isn't defined that way. In Java, we tend to write down everything quite explicitly, and I personally like it that way, as it generally improves code reliability.

Imagine a small typo:

public Car (int xDistance, int yDistance, int gas) {
}

If I'd read that, I'd expect that to initialize the three fields. But how will the compiler interpret that? xDistance and yDistance will now simply be normal constructor arguments, not initializing any field. Depending on your IDE / compiler settings, you might at best get an "unused argument" warning. So, I strongly prefer not having such a fragile automatic initialization.

And for boilerplate code like such a constructor, e.g. Eclipse has the "Source / Generate constructor using fields..." wizard. A few clicks, and you have the constructor.

Licensed under: CC-BY-SA with attribution
scroll top