toString() method belongs to object class.
class Student{
String name;
int id;
String city;
Student(String name, int id, String city){
this.name = name;
this.id = id;
this.city = city;
}
public String toString(){
return " Name: "+name + " id: "+id + " city: "+city;
}
public static void main(String[] args){
Student S1 = new Student("Dj", 111, "Irving");
Student S2 = new Student("Rabi", 222, "Dallas");
System.out.println(S1);
System.out.println(S2);
}
}
Now, the output will be:
Name: Dj id: 111 city: Irving
Name: Rabi id: 222 city: Dallas
If we don't use the toString() method and directly print the object, we get some garbage values that we cannot understand.
No comments:
Post a Comment