1

我对如何将我的课程转换为Integer. 例子:

public class IntegerField extends Field {
    private Integer value;
    public IntegerField(Integer value) {
        super();
        this.value = value;
    }
    public int intValue() {
        return value;
    }
}

我该怎么做:

IntegerField a = new IntegerField(8);
Integer b = (Integer) a;

谢谢!

4

2 回答 2

4

No. You can't define your own conversion operators in Java. However, it's simple to add a method:

public class IntegerField extends Field {
    private Integer value;
    public IntegerField(Integer value) {
        super();
        this.value = value;
    }

    public Integer toInteger() {
        return value;
    }
}

...

IntegerField a = new IntegerField(8);
Integer b = a.toInteger();

Why would you prefer a cast?

(Note that I've removed the intValue method which would throw an exception if value is null. The caller of toInteger can always convert to int if they want that behaviour.)

于 2013-02-23T19:28:08.017 回答
0

整数 b = (整数) a; --- 不正确,因为 value 是私有的,你必须写一个方法来获取 value,Integer b = a.intValue();

于 2013-02-23T19:33:13.203 回答