如何设置一个等于文字的对象?

时间:2016-05-12 00:30:20

标签: java literals

我想创建一个可以存储整数值并在其上调用各种方法的对象。代码就像这样

public class IntegerUtil{
private int value;

public IntegerUtil(int a){
this.value = a;
}

//insert methods here

}

当我实例化IntegerUtil对象时,我会执行类似

的操作
IntegerUtil iu = new IntegerUtil(5); //this does compile

我更愿意这样做,而不是输入整个构造函数。

IntegerUtil iu = 5; //this does not compile

编译器不接受此作为有效语法,因为我将非原始数据类型设置为等于文字。但是有可能做到这一点。我注意到java.lang.Integer类可以设置为等于文字。

int integer = 5; //primitive data type set equal to literal
Integer integer = 5; //object set equal to literal - how to do this?
Integer integer = new Integer(5); //object being instantiated with constructor
//all three of these compile with no problem

有没有办法可以让我的IntegerUtil对象像java.lang.Integer类一样运行,因为它可以初始化为文字?

0 个答案:

没有答案
相关问题