Java Property Syntax

  by Ronald Koster, version 2.0, 2007-07-26

How to get rid of obsolete getters and setters in Java

In most cases in Java getters and setters are trivial. Still you need to code them. This leads to a lot of obsolete code. One way to overcome this would be to introduce the new Java keyword: property. Its usage would have to be like this:
public class Example {
	property SomeType variable;
}
Is equivalent to:
public class Example {
	private SomeType variable;

	public SomeType getVariable() {
		return this.variable;
	}

	public void setVariable(SomeType variable) {
		this.variable = variable;
	}
}
As can be seen a property has a public getter and setter by default. However, in case an explicitly coded getter or setter is present it overrides the default getter/setter.
Example with protected getter and public setter:
public class Example {
	property SomeType variable;

	protected SomeType getVariable() {
		return this.variable;
	}
}

Example with public getter and package setter:
public class Example {
	property SomeType variable;

	void setVariable(SomeType variable) {
		this.variable = variable;
	}
}

NB.1. Of cource when one needs a field not to be visible from outside the class, use an old fashioned private field:

public class Example {
	private SomeType variable;
}

NB.2. For backward compatibility it is perhaps a problem to introduce a new keyword property. A possible solution is to name it proprty instead.

Prohibit non-private fields

Another related good idea would be to prohibit non-private fields. With one exception: when the have the final modifieer they can be non-private. So the next code should give a syntax error:
public class Example {
	SomeType variable; // not allowed
}
But this code is OK:
public class Example {
	public final SomeType variable; // OK
}