简体   繁体   中英

Is it possible to create my own primitive datatype in java. like int, float,double

How to create my own datatype in java, that will accept value range from 0 to 1024.

My declaration would be.

kilobyte a=10;

Is it possible?

No. Java doesn't allow that (ie creating a primitive). But you could create your own class for that.

You cannot create your own primitive, but you could have a wrapper Object for that.

Dirty example here:

// note that class name doesn't follow Java conventions here
public class kilobyte {
    private int number;

    public kilobyte(Number number) {
        if (number == null) {
            throw new IllegalArgumentException("argument is null");
        }
        else if (number.intValue() > 1024 || number.intValue() < 0) {
            throw new IllegalArgumentException("argument not within 0 < x < 1024 range");
        }
        else {
            this.number = number.intValue();
        }
    }
    // TODO getter/setter
}

不,您不能创建自己的原始类型,也不能重载运算符,因此在Java中是不可能的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM