![](/img/trans.png)
[英]Java - What happens when we create a data type of type class in its own class?
[英]What happens when we create instance of Integer class in java
我对以下代码感到困惑:
import java.util.*;
public class HelloWorld {
private int x;
public HelloWorld(int x) {
this.x = x;
}
public static void main(String[] args) {
HelloWorld o1 = new HelloWorld(5);
HelloWorld o2 = new HelloWorld(5);
System.out.println(o1);
System.out.println(o2);
Integer i = new Integer(1);
Integer j = new Integer(10);
System.out.println(i);
System.out.println(j);
}
}
显然,我创建了两个 HelloWorld 类对象和两个 Integer 类对象。 当我打印它们时,输出如下:
HelloWorld@6d06d69c
HelloWorld@7852e922
1
10
我的疑问是当我创建 helloWorld 类的对象时,对象存储了一些引用,但是当我创建 Integer 类的实例时,这些值存储在对象中。 为什么会发生这种情况。
有没有办法直接在 HelloWorld 类对象中存储值。
我还注意到,每当我为 Java 中的任何内置类(如 String、Character、List、Map……)创建对象时,它们都存储值。 那么这些内置类中另外存在的是什么。
我的疑问是当我创建 helloWorld 类的对象时,对象存储了一些引用,但是当我创建 Integer 类的实例时,这些值存储在对象中。
不,在这两种情况下,该值都存储为实例( HelloWorld
或Integer
)中的字段。
有没有办法直接在 HelloWorld 类对象中存储值。
这就是你的代码所做的。
如果要更改HelloWorld
类的实例转换为字符串的方式,请覆盖toString
。 例如:
@Override
public String toString() {
return String.valueOf(this.x);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.