关于 Java 两个 Integer 相加的问题
資深大佬 : pkookp8 13
小弟刚开始学 Java,了解到 Java 没有操作符重载 所以使用+操作符对两个类进行相加应该是做不到的
于是对这段代码不是很理解了
class Integer { private int value; public Integer(int value) { this.value = value; } public int intValue() { return this.value; } public static Integer valueOf(int i) { return new Integer(i); } } public class Main { public static void main(String[] argv) { java.lang.Integer zz = 1; java.lang.Integer xx = 2; //调用 java.lang.Integer.valueOf(2),返回 java.lang.Integer.Integer 类型 java.lang.Integer aa = zz + xx; //zz + xx 是如何实现的? System.out.printf("%sn", aa); //printf 的时候可以直接把 aa 打印出来,这又是怎么做到的? //Integer a = 1; //Type mismatch: cannot convert from int to Integer //Integer x = Integer.valueOf(1); //Integer y = Integer.valueOf(2); //Integer z = x + y; //The operator + is undefined for the argument type(s) Integer, Integer //请问如何自己实现 x+y? //System.out.printf("%sn", z); //似乎打印了地址, [email protected] } }
尝试用了断点的方式,发现 zz + xx 似乎会进入两次 java.lang.Integer.intValue 函数
也就是说 zz 调用了 java.lang.Integer.intValue,返回了 int 类型的 1
xx 返回了 int 类型的 2
然后进入了 java.lang.Integer.valueOf(3)
printf 的时候可以直接把 aa 打印出来
问题
- java.lang.Integer 是怎么实现 Integer a = 1;而不报错“Type mismatch: cannot convert from int to Integer”的?
- java.lang.Integer 又是如何实现 x+y?
- java.lang.Integer 还能直接用%s 打印
不知道用什么关键词搜索这些问题
大佬有話說 (1)