6 java encapsulation properties private-members
可能重复:
Java中缺少属性语法
请参阅以下情况:
class Test extends Object {
private int x;
public getX() {return x;}
public setX(int _x) {x = _x;}
}
Run Code Online (Sandbox Code Playgroud)
如你所见,没什么特别的.但是,我想知道是否可以保持"私有x"的方式,使用该类的人不需要使用getX(),换句话说,如果我可以映射一些自动调用的变量得到并设定.
像德尔福的"财产"之类的东西.它可以避免在复杂表达式中使用setX()和getX(),并且可以简化对谁读取表达式的理解.
例如,假设可以使用另一个标识符xx和yy来代替get和set方法.看到:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望你们这里得到我的意思.
编辑:
Rolly绉!这是很多答案!非常感谢大家.
use*_*383 17
你可以通过反射来访问它们
Test test = new Test()
Field field = test.getClass().getDeclaredField("x");
field.setAccessible(true);
System.out.println(field.getName() + "="+field.get(test ));
Run Code Online (Sandbox Code Playgroud)
但是,你不应该这样做
小智 6
我认为你正在尝试将它理想化为C#属性,如下面的代码,对吧?:
public sealed class Example {
private int _code;
private string _name;
public Example(int code) {
this._code = code;
}
public int Code {
get {return this._code;}
set {this._code = value;}
}
public string Name {
set {this._name = value;}
get {return this._name;}
}
public override string ToString() {
return this._code.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我认为我们没有这样的手段,但我也没有看到使用getter和setter没什么不对.
| 归档时间: |
|
| 查看次数: |
5965 次 |
| 最近记录: |