Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a Java Number subclass automatically box and unbox?

Tags:

java

I am creating some classes to represent Unsigned numbers for Java and deriving them from Number. One of my goals is to make them box and unbox primitive values but I can't get this to work nor find any discussion of how to achieve this elsewhere.

Can this be done and if so how?

Here is my not working code!

public class Unsigned8 extends Number implements Comparable<Unsigned8>{

public static final long MAX_VALUE = 256L;
public static final long MIN_VALUE = 0;
private long _Value;


public Unsigned8(long value)
{
    this._Value = value;
}

@Override
public byte byteValue() {
    return (byte) _Value;
}

@Override
public short shortValue() {
    return (short) _Value;
}

@Override
public int intValue() {
    return (int) _Value;
}

@Override
public long longValue() {
    return (long) _Value;
}

@Override
public double doubleValue() {
    return _Value;
}

@Override
public float floatValue() {
    return _Value;
}

@Override
public int compareTo(Unsigned8 target) {
    return (int) (_Value - target._Value);
}

}

like image 469
Howard May Avatar asked Feb 19 '23 23:02

Howard May


2 Answers

You can't. What I do is use an Unsigned helper class for short int and long so that your don't incur the overhead of a wrapper to support unsigned types. See the link for examples.

like image 164
Peter Lawrey Avatar answered Feb 26 '23 12:02

Peter Lawrey


No. You get a relation between primitives and its wrapper that follows:

Primitive type  Wrapper class
boolean         Boolean
byte            Byte
char            Character
float           Float
int             Integer
long            Long
short           Short

They are limited to these types. Documentation here

like image 22
Francisco Spaeth Avatar answered Feb 26 '23 10:02

Francisco Spaeth