gpt4 book ai didi

Java-String对象和用户定义对象的区别

转载 作者:行者123 更新时间:2023-12-02 11:15:36 25 4
gpt4 key购买 nike

这是一个简单的java程序。它包含一个类“Student”,我们将其两个对象设为stud,stud1。同样,我还创建了一个 String 对象“a”,其值为“Hello”。

class Student{

int age;

public void setAge(int age){
this.age=age;
}

public int getAge(){
return age;
}
}


class Hello{

public static void main(String args[]){

Student stud= new Student();
Student stud1= new Student();
stud.setAge(15);
int i=stud.getAge();
String a=new String("Hello");
System.out.println(stud);
System.out.println(stud1);
System.out.println(a);
}

}

正如我们所知,当我们创建一个类对象时,它只保存该对象的引用值。这就是为什么当我尝试打印 Stud 和 Stud1 时,我得到两个引用值。但是因为“a”是类的对象我们应该期待一个引用值而不是值“Hello”的字符串。为什么会发生这种情况?

最佳答案

这一行

System.out.println(stud);

相当于1

System.out.println(stud.toString());

字符串 overrides Object.toString方法在打印字符串时得到比一堆字符和数字更有意义的东西。

您也可以让您的用户定义的类执行此操作。在您的 Student 类中,它看起来像这样:

class Student{

int age;

public void setAge(int age){
this.age=age;
}

public int getAge(){
return age;
}

@Override
public String toString() { // Called for instance when
return "Student with age " + age; // the student should be printed
}
}

这是一个ideone.com demo运行您的代码,其中 Student 覆盖 toString

进一步阅读:

1) 除非螺柱等于 null

关于Java-String对象和用户定义对象的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9771688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com