Motivation
understanding deeply what happens when we print object in java.
Background
we have a list of employee object and we are trying to print that
Example
empList.stream().forEach(e -> System.out.println(e));
here we are printing the object so what is the output here.
practiceJava.Employee@87aac27
practiceJava.Employee@3e3abc88
Explaination
out put here is the class name at and then location where object is stored in the memory.
when we print any object in java first it will look for toString method in the same class if the method is there that will be used , if method is not there it will go to parent or super class if method is there that will be used, and if no method is there, it will go to the parent class that is object class where toString method is defined which will print classname and location of object stored in memory
Further
- Definition of toString in Object Class
- Define toString in Employee Class and then print object
- Define toString only in the parent object class and then check output
Definition of toString in Object Class
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
Define toString in Employee Class and then print object
public String toString() {
return this.name;
}
Output
sandy
amit
Define toString only in the parent object class and then check output
- in that case parent definition is used, if defined in both child and parent in that case child definition is being used.