2015-09-11问题(二)

1.Integer a=new Integer(6);//????
System.out.println(a);//输出的值怎么还是6???

 (1)每个对象中都有一个(继承或者重新)toString()方法,这个方法一般用于输出一些和对象相关的信息。Integer的toString()方法如下:

 1  /**
 2      * Returns a {@code String} object representing this
 3      * {@code Integer}'s value. The value is converted to signed
 4      * decimal representation and returned as a string, exactly as if
 5      * the integer value were given as an argument to the {@link
 6      * java.lang.Integer#toString(int)} method.
 7      *
 8      * @return  a string representation of the value of this object in
 9      *          base 10.
10      */
11     public String toString() {
12         return toString(value);
13     }

由注释可知,Integer的toString()方法返回Integer对象对应的那个int类型值的字符串形式。

1 //测试Integer的toString方法的返回结果
2           Integer num=new Integer(61);
3           String s = num.toString();
4           //判断引用s指向对象类型
5           if(s instanceof String)
6               System.out.println("String类型引用变量s指向的那个对象是一个String对象!");
7           //判断s指向对象包含的内容
8           if(s.equals("61"))
9               System.out.println("s="+61);

(2)当这种情况时:System.out.println(对象的引用(非String类型引用)),引用指向的对象的toString方法会被调用,然后将调用结果输出到控制台。例如这里的System.out.println(a);引用a指向的Integer对象的toString()方法会被调用,并被输出到控制台。由(1)可知。调用结果是字符串"6".并被输出到了控制台.所以你在控制台看到的是6而不是  Integer@n个数字

 

posted @ 2015-09-11 00:04  老司机飙车  阅读(181)  评论(0编辑  收藏  举报