gpt4 book ai didi

java - 如何打印类字段的值以及父类字段的值?

转载 作者:行者123 更新时间:2023-12-01 10:19:27 38 4
gpt4 key购买 nike

这是我 child 的类(class)。我想用 toString 方法打印字段的值。任何人都可以帮助我如何打印子类字段以及父类字段

public class Student extends StudentAddress {

private String studentName;
private String courseName;


public Student(
String address1,
String address2,
int mob,
String studentName,
String courseName) {
super(address1, address2, mob);
this.studentName = studentName;
this.courseName = courseName;
}

public void display(Student s){
System.out.println(s.toString());
}

public static void main(String[] args) {
Student student = new Student("add1","add2",122,"Abc","MMC");
System.out.println(student);
student.display(student);
}


@Override
public String toString() {
return "Student{" +
"studentName='" + studentName + '\'' +
", courseName='" + courseName + '\'' +
'}';
}
}

这是父类。

public class StudentAddress {

private String address1;
private String address2;
private int mob;

public StudentAddress(String address1, String address2, int mob) {
this.address1 = address1;
this.address2 = address2;
this.mob = mob;
}

@Override
public String toString() {
return "StudentAddress{" +
"address1='" + address1 + '\'' +
", address2='" + address2 + '\'' +
", mob=" + mob +
'}';
}
}

我想打印所有 5 个字段的值;

最佳答案

Student中,使用super.toString()

public String toString() {
return "Student{" +
"studentName='" + studentName + '\'' +
", courseName='" + courseName + '\'' +
'}'+super.toString();
}

当然,我不知道您想要如何格式化输出,因此请根据需要进行必要的更改。

关于java - 如何打印类字段的值以及父类字段的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35706108/

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