Reputation: 211
This is my child class. i want to print values of fields with toString method. can any one plz help me how i print child class fields as well parent class fields
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 + '\'' +
'}';
}
}
This is parent class.
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 +
'}';
}
}
I want print all the 5 fields values;
Upvotes: 0
Views: 957
Reputation: 8354
in Student
, use super.toString()
public String toString() {
return "Student{" +
"studentName='" + studentName + '\'' +
", courseName='" + courseName + '\'' +
'}'+super.toString();
}
of course i don't know how you want to format the output , so make necessary changes as needed.
Upvotes: 1