C#中可以使用属性使数据字段公开访问(允许用户直接访问它),但仍然保留对这些直接访问字段执行数据验证的能力。 Java有类似的功能吗?例如,假设存在一个具有以下实现的C#类(见下文):
public class newInt{
public newInt(){...}
public int x{
get{ return this.x }
set{ this.x = isValid(value) }
}
}
private static int isValid(int value){...}
在该类中定义的这个方法允许用户在从数据字段'x'中检索值和给它分配值时使用更加自然的方式。以下是其在主函数中的使用示例。
public class Test{
public static void main(String[] args){
newInt a = new newInt();
a.x = 50;
int b = a.x;
}
}
问题是... Java 是否也能做到这一点?如果可以,它叫什么名字?