0

I am wanting to create an object that can store an integer value and call various methods on it. The code is like this

public class IntegerUtil{
private int value;

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

//insert methods here

}

When I instantiate an IntegerUtil object, I do something like

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

I would prefer to do this instead of typing out the entire constructor.

IntegerUtil iu = 5; //this does not compile

The compiler doesn't accept this as valid syntax because I am setting a non primitive data type equal to a literal. But it is possible to do this. I noticed that the java.lang.Integer class can be set equal to a literal.

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

Is there a way I can make my IntegerUtil object behave like the java.lang.Integer class in that it can be initialized as a literal?

  • 3
    [Autoboxing](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html) is a special compiler feature for specific primitive wrappers. You can't apply it on your own. – shmosel May 12 '16 at 00:32
  • 1
    If you want a slightly shorter syntax, you can create a static factory method and use a static import to do `IntegerUtil iu = wrap(5);`. – shmosel May 12 '16 at 00:35
  • You'd need something like Swift's `IntegerLiteralConvertible`, but there is no such thing in Java. You'll have to live with calling a constructor or factory method. – Thilo May 12 '16 at 00:40
  • @thilo What was the problem with the duplicate? – Sotirios Delimanolis May 12 '16 at 00:44
  • @SotiriosDelimanolis: It talks more about how to make Map literals, not how to do something like `MyObject x = 123`. So I think this one deserves a fresh answer (or another duplicate). – Thilo May 12 '16 at 01:13
  • @Thilo I think it's pretty clear that it means _any literal syntax_ is disallowed for custom types and even lists all the solutions proposed here in the comments. – Sotirios Delimanolis May 12 '16 at 01:14
  • 1
    @Thilo [Here you go](http://stackoverflow.com/questions/18386773/set-custom-class-objects-value-with-operator-in-java). – Sotirios Delimanolis May 12 '16 at 01:31
  • Related: [initialize object directly in java](http://stackoverflow.com/questions/12005584/initialize-object-directly-in-java) – Sotirios Delimanolis May 12 '16 at 01:36

0 Answers0