In: Computer Science
Kindly note that toString() method is defined in Object Class in Java and since any Class in Java is actually an Object of the Object Class , hence all classes already have a defined toString() method. If you simply print a Object (System.out.println(obj)). This invokes the toString() method and a output is returned. Originally , this output is the hashcode of the current object. Hence , we need to override the toString() method to print information as per our requirement.
Here is the complete implementation
class Cat{
/* Attributes are private to provide more abstraction and therefore other classes need to use getter and setter functions to access these attributes */
private String breed;
private String name;
private double weight;
/* Class Constructor for initialisation of attributes */
public Cat(String breed , String name , double weight){
this.breed = breed;
this.name = name;
this.weight = weight;
}
/* Setter Functions */
public void setBreed(String breed){
this.breed = breed;
}
public void setName(String name){
this.name = name;
}
public void setWeight(double weight){
this.weight = weight;
}
/* Getter Functions */
public String getBreed(){
return breed;
}
public String getName(){
return name;
}
public double getWeight(){
return weight;
}
/* Overriding toString function as it is already defined in the Object Class
and if you call toString() without overriding it in your class , the output
will be the hashCode of the Object Eg:- Cat@453290 where last 6 digits are
hashcode of the object. Hence , we need to override the method*/
@Override
public String toString(){
return ("Breed is : "+breed+", Name is : "+name+
", Weight is : "+weight+ "---WELCOME CAT---");
}
}
public class HelloWorld{
public static void main(String []args){
/* Creating two different objects */
Cat C1=new Cat("Persian","Bella",6);
Cat C2=new Cat("Maine Coon","Lucy",9);
/* Calling their toString method , which can be done by simple printing
the object in Java*/
System.out.println(C1);
System.out.println(C2);
}
}
Here is the screenshot of the output.