我有一个自定义对象,它有一个 int 类型的值,我想对其进行处理以将该值保持在设定的范围内。我的问题是:给定以下类,我可以用 myObject = 0 设置它的值吗?
public class foo{
private int bar;
public foo(){
}
}
而不是创建一个方法 public void setBar()
我有一个自定义对象,它有一个 int 类型的值,我想对其进行处理以将该值保持在设定的范围内。我的问题是:给定以下类,我可以用 myObject = 0 设置它的值吗?
public class foo{
private int bar;
public foo(){
}
}
而不是创建一个方法 public void setBar()
如果你的意思是:
foo x = new foo();
x = 10; // This is meant to set x.bar
那么不,你不能在Java中做到这一点。好东西,如果你问我......这在可读性方面会很糟糕。
您也不能将其更改为允许:
foo x = 10;
相当于:
foo x = new foo();
x.bar = 10; // Or x.setBar(10);
不,你不能那样做。Java 不支持运算符重载。尽管+
运算符为执行字符串连接而重载,但这是唯一的例外。另一个=
以您想要的方式使用运算符的示例是在包装器类的情况下,您可以直接将原始类型值分配给它对应的包装器类型,这会导致原始值自动装箱到包装器类型。
Integer val = 10; // 10 is auto-boxed to Integer reference
但它仅限于此目的。您不能为自己的用户定义类型这样做。
创建方法是您唯一的选择。
Foo myObject = new Foo();
Here, myObject
holds the reference. You can't assign primitive value such as 0 to object references.
Instead, you should do myObject.setBar(10);
In Java, the convention is to provide setters and getters to change an object's inner attributes. For your case:
foo instance = new foo();
instance.setBar(10); //Sets bar to 10
instance.getBar(); //returns bar's current value (right now 10)
The setter receives the new value and sets it:
public void setBar(int newBar) {
bar = newBar;
}
And the getter gives access to the field's current value:
public int getBar() {
return bar;
}
You cannot, however, overload the =
operator to do as setBar
does, at least in Java. If you're thinking about, for example the Integer
or Float
wrapper classes, there's another force at work there, related to Java's implementation itself and that later derives in the concepts of boxing and unboxing.
另一种可能性是,您可以将此字段公开。它只需要在业务方法中进行您需要的验证(在设置期间不需要)。
不,它违背了封装逻辑和 Java 本身。