If have the following class …
/**
* Two dimensional cartesian point.
*/
public class Point {
public final double x;
private final double y;
public double y(){
return this.y;
}
}
I can retrieve values as follows Point.x or Point.y()
I thought it was good practice in OO languages to encapsulate data by not making it directly accessible and instead using accessors, but it would seem that using directly field access is more normal and readable.
Why doesn’t Java allow me to dispense which the ()’s for function calls that take no parameters.
When you think about it, code would become completely unreadable. When you encountered something like
foo.bar, yhou wouldn’t know whether it was accessing a field, or calling a method.It could only work if you introduced a third kind of construct besides fields and methods: properties. If Java supported properties, accessing them without
()would not harm readability. There’s no technical reason for why there are no property-like constructs in Java, it was just a design decision.But allowing the omission of parentheses in any method call without a parameter is a bad idea.