java program to print the object of class by overriding the toString() method
import java.util.*;
public class PrintClassObjectDemo
{
public static void main (String[] args) {
Student s1=new Student(1,"Brijesh","Kld");
Student s2=new Student(2,"Kumar","GKP");
System.out.println(s1);
System.out.println(s2);
Employee e1=new Employee(1,"Brijesh","CSE");
Employee e2=new Employee(2,"Kumar","IT");
System.out.println(e1);
System.out.println(e2);
//the instance of Employee will produce hash code of
//instance , so we need to override the toSting()
//method to avoid such mistakes.
}
}
public class Student{
int rollno;
String name;
String city;
Student(int rollno,String name,String city)
{
this.rollno=rollno;
this.name=name;
this.city=city;
}
//overriding toString() method.
public String toString()
{
return rollno+" "+name+" "+city;
}
}
public class Employee
{
int id;
String name;
String department;
Employee(int id,String name,String department)
{
this.id=id;
this.name=name;
this.department=department;
}
//this will print hashcode of object because it is not
//overriding toString() method
}