Eli Sadoff - 3 months ago 14

Java Question

Java's literal initializers are mostly used for primitives (e.g.

`int i = 2`

`double j = 4.2`

`String a = "Hello"`

`Number z = 43`

`Numeric`

`Number`

`Numeric a = 43`

Here is the part of the source code for

`Numeric`

`public class Numeric extends Number {`

private HashMap<Primitive, Number> values;

private Primitive origin;

public Numeric(byte value) {

values = new HashMap<>();

values.put(Primitive.BYTE, value);

values.put(Primitive.SHORT, (short) value);

values.put(Primitive.INT, (int) value);

values.put(Primitive.LONG, (long) value);

values.put(Primitive.FLOAT, (float) value);

values.put(Primitive.DOUBLE, (double) value);

origin = Primitive.BYTE;

}

public Numeric(short value) {

values = new HashMap<>();

values.put(Primitive.BYTE, (byte) value);

values.put(Primitive.SHORT, value);

values.put(Primitive.INT, (int) value);

values.put(Primitive.LONG, (long) value);

values.put(Primitive.FLOAT, (float) value);

values.put(Primitive.DOUBLE, (double) value);

origin = Primitive.SHORT;

}

public Numeric(int value) {

values = new HashMap<>();

values.put(Primitive.BYTE, (byte) value);

values.put(Primitive.SHORT, (short) value);

values.put(Primitive.INT, value);

values.put(Primitive.LONG, (long) value);

values.put(Primitive.FLOAT, (float) value);

values.put(Primitive.DOUBLE, (double) value);

origin = Primitive.INT;

}

public Numeric(long value) {

values = new HashMap<>();

values.put(Primitive.BYTE, (byte) value);

values.put(Primitive.SHORT, (short) value);

values.put(Primitive.INT, (int) value);

values.put(Primitive.LONG, value);

values.put(Primitive.FLOAT, (float) value);

values.put(Primitive.DOUBLE, (double) value);

origin = Primitive.LONG;

}

public Numeric(float value) {

values = new HashMap<>();

values.put(Primitive.BYTE, (byte) value);

values.put(Primitive.SHORT, (short) value);

values.put(Primitive.INT, (int) value);

values.put(Primitive.LONG, (long) value);

values.put(Primitive.FLOAT, value);

values.put(Primitive.DOUBLE, (double) value);

origin = Primitive.FLOAT;

}

public Numeric(double value) {

values = new HashMap<>();

values.put(Primitive.BYTE, (byte) value);

values.put(Primitive.SHORT, (short) value);

values.put(Primitive.INT, (int) value);

values.put(Primitive.LONG, (long) value);

values.put(Primitive.FLOAT, (float) value);

values.put(Primitive.DOUBLE, value);

origin = Primitive.DOUBLE;

}

`Primitive`

`enum`

Answer

`String`

literals as a special case in Java. `Number`

s don't really have literals - what you're seeing here is a primitive (such as 2) being autoboxed to its wrapper class (such as `Integer`

). Since all the numeric wrappers extends `Number`

, this assignments works (in the same way that `Object o = 4;`

would be a legal statement).

You can not add your own literals to the language, though. The best you could do is to create some static function that produces a new instance of your class.