在Java中使用'='运算符设置自定义类对象的值 [英] Set custom class object's value with '=' operator in Java

查看:174
本文介绍了在Java中使用'='运算符设置自定义类对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义对象,它有一个int类型的值,我想要进行处理以将此值保持在设定范围内。我的问题是:给定下面的类,我可以用myObject = 0设置它的值;

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

而不是创建方法public void setBar()

Instead of creating a method public void setBar()

推荐答案

如果您的意思是:

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

然后不,你不能用Java做到这一点。好的,如果你问我......在可读性方面会很糟糕。

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

无法改变它允许:

foo x = 10;

相当于:

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

这篇关于在Java中使用'='运算符设置自定义类对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆