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

时间:2016-02-29 17:50:40

标签: java

这是我的孩子班。我想用toString方法打印字段的值。可以任何一个plz帮助我如何打印子类字段以及父类字段

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个字段值;

1 个答案:

答案 0 :(得分:1)

<{1>}中的

,请使用Student

super.toString()

当然我不知道你想如何格式化输出,所以根据需要进行必要的修改。