Possible Duplicate:
Absence of property syntax in Java
See the following situation:
class Test extends Object {
private int x;
public getX() {return x;}
public setX(int _x) {x = _x;}
}
As you can see, nothing special. However, I'd like to know if it's possible to keep that "private x" in a way that someone using the class don't need to use getX(), in other words, if I could map some variable that automatically called the gets and sets.
Something like the "property" in Delphi. It'd prevent the need of using setX() and getX() in a complex expression and would ease the understanding of who reads the expression.
For example, suppose another identifier xx and yy could be used in place of the get and set methods. See:
import Test;
public static void main(String[] args) {
new Test() {
setX(10);
setY(20);
int z = getX() * getY() + (getY() * getY());
System.out.println("%d", z);
}
// would be like this
new Test() {
xx = 10;
yy = 20;
int z = xx * yy + (yy * yy); // xx would access the method getX() automatically
System.out.println("%d", z);
}
}
I hope you guys got what I mean here.
EDIT:
Rolly crepe! That's a lot of answers! Thank you very much, everyone.
You can't.
That's why we talk in "encapsulation". Only if you change or modify from private to something else or if you use reflection (what would make it even more complicated).
I don't see any problem in using the famous getters and setters.