In Java, the Object class is the root class of all classes. Every class automatically inherits methods from the Object class, even if it does not explicitly extend it.
java.lang packageSome commonly used methods of the Object class are:
toString()equals(Object obj)hashCode()getClass()clone()finalize()
// Demonstrating Object class methods
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id + " " + name;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(1, "Rahul");
Student s2 = new Student(1, "Rahul");
System.out.println(s1.toString());
System.out.println(s1.equals(s2));
System.out.println(s1.getClass());
System.out.println(s1.hashCode());
}
}
1 Rahul
false
class Student
(Generated hash code value)
Explanation:
toString() returns object detailsequals() compares reference by defaultgetClass() returns runtime classhashCode() returns unique integer
Enter data for two objects. See how equals() behaves with and without overriding.
toString() for readable outputequals() and hashCode() togethergetClass() for runtime type checksfinalize() (deprecated)equals() to compare object valuesgetClass() method