Set custom class object's value with '=' operator in Java

依然范特西╮ 提交于 2019-12-19 19:49:14

问题


I have a custom object that has a single value of type int that I wanting to do processing on to keep this value in a set range. My question is this: Given the following class, can I set it's value with myObject = 0;

public class foo{
    private int bar;
    public foo(){
    }
}

Instead of creating a method public void setBar()


回答1:


If you mean:

foo x = new foo();
x = 10; // This is meant to set x.bar

then no, you can't do that in Java. Good thing too, if you ask me... it would be horrible in terms of readability.

You also can't change it to allow:

foo x = 10;

as equivalent to:

foo x = new foo();
x.bar = 10; // Or x.setBar(10);



回答2:


No you can't do that. Java does not support operator overloading. Although + operator is overloaded for performing String concatenation, but that's the only exception. Another example that uses the = operator the way you would want is in case of wrapper classes, where you can directly assign a primitive type values to it's corresponding wrapper type, which causes the primitive value to be auto-boxed to wrapper type.

Integer val = 10;  // 10 is auto-boxed to Integer reference

But it's only limited for that purpose. You can't do that for your own user-defined type.

Creating a method is your only option.




回答3:


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);




回答4:


No, it goes against encapsulation logic, and Java Itself.




回答5:


Abother possibility, you could make this field public. It would just need to do the validations you need in the business method (no during the set).




回答6:


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.



来源:https://stackoverflow.com/questions/18386773/set-custom-class-objects-value-with-operator-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!