Set custom class object's value with '=

2019-02-22 10:34发布

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

6条回答
够拽才男人
2楼-- · 2019-02-22 10:36

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

查看更多
祖国的老花朵
3楼-- · 2019-02-22 10:44

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);
查看更多
来,给爷笑一个
4楼-- · 2019-02-22 10:47

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.

查看更多
Summer. ? 凉城
5楼-- · 2019-02-22 10:51

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

查看更多
来,给爷笑一个
6楼-- · 2019-02-22 11:00

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.

查看更多
Rolldiameter
7楼-- · 2019-02-22 11:00

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

查看更多
登录 后发表回答