简体   繁体   English

Java中普通类对象和包装器类对象有什么区别

[英]What is the difference between a normal class object and a wrapper class object in java

Normally when I try to print an object using System.out.println(); 通常,当我尝试使用System.out.println();打印对象时System.out.println();

class Car {
    String color = "red";
}

class Main {
    public static void main(String[] args) {
        Car car = new Car();
        System.out.println(car);
    }
}

The output is something like: 输出类似于:

Car@677327b6

Which is its class name + '@' + hashCode . 它的class name + '@' + hashCode And internally it is calling the toString() method. 在内部,它正在调用toString()方法。 This seems good. 好像很好 But what happens when I implement autoboxing as follows: 但是当我实现自动装箱如下时会发生什么:

class Main {
    public static void main(String[] args) {
        int i = 100;
        Integer obj = i;
        System.out.println(obj);
    }
}

Here the output is 100 . 这里的输出是100 Why it is not like Main@hexcode ? 为什么它不像Main@hexcode I thought I'm converting the primitive i to an object of type Integer . 我以为我会将原始i转换为Integer类型的对象。 Please correct me. 请纠正我。

Class@hashCode is the default return value of Object.toString() . Class @ hashCode是Object.toString()的默认返回值。 The Integer class overrides toString() . Integer覆盖toString()

 public String toString() 

Returns a String object representing this Integer 's value. 返回表示此Integer值的String对象。 The value is converted to signed decimal representation and returned as a string, exactly as if the integer value were given as an argument to the toString(int) method. 该值将转换为带符号的十进制表示形式,并以字符串形式返回,就像将整数值作为toString(int)方法的参数给出一样。

Overrides: 覆写:
toString in class Object Object toString

Returns: 返回值:
a string representation of the value of this object in base 10. 以10为基数的此对象的值的字符串表示形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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