You are on page 1of 2

1-override……..

class Student{
int id;
String name;
String address;

Student(int id, String name, String address){


this.id=id;
this.name=name;
this.address=address;
}

public static void main(String args[]){


Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);

System.out.println(s1);//compiler writes here s1.toString()


System.out.println(s2);//compiler writes here s2.toString()
}
}
………………………..

You can see in the above example #1. printing s1 and s2 prints the Hashcode values of the
objects but I want to print the values of these objects. Since java compiler internally calls
toString() method, overriding this method will return the specified values. Let's understand it
with the example given below:

Example#2

Output with overriding toString() method

class Student{
int id;
String name;
String address;

Student(int id, String name, String address){


this.id=id;
this.name=name;
this.address=address;
}

//overriding the toString() method


public String toString(){
return id+" "+name+" "+address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);

System.out.println(s1);//compiler writes here s1.toString()


System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:100 Joe success
50 Jeff fail
Note that toString() mostly is related to the concept of polymorphism in Java. In, Eclipse, try
to click on toString() and right click on it.Then, click on Open Declaration and see where the
Superclass toString() comes from.

……………………………………………………………….

You might also like