Why does every class in Java extend Object, and what methods does that give you for free?
Every class in Java extends the class java.lang.Object, whether you write it or not. If you write class Main, the compiler really means class Main extends Object.
The class Object is the most basic class there is, and it gives every object a common set of methods.
The method toString gives you a text form of the object. The method equals compares two objects, and by default it asks whether they are the same object rather than whether they hold the same data. The method hashCode gives you a number that is worked out from the data, and it is what makes an object usable as a key in a hash map. The method getClass tells you the exact class of the object at run time.
public class Main {
public static void main(String[] args) {
// A String is an Object too.
Object anything = "a string is an Object too";
System.out.println("text : " + anything);
System.out.println("class : " + anything.getClass().getName());
System.out.println("is a string : " + (anything instanceof String));
// Your own class gets all of the same methods for free.
Point point = new Point(1, 2);
System.out.println("default toString : " + point);
System.out.println("hash code : " + point.hashCode());
}
}
class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
There is a reason this design is so useful. Because every object has these methods, you can write code that works with any object at all. A method that takes an Object can print it, compare it, or put it in a collection, without knowing what it really is.
Two of the methods in Object are worth overriding as soon as you write a class of your own. The method toString should say what the object is, so that it prints nicely. And the method equals should say what it means for two objects of your class to be the same, and when you override it you must override hashCode as well.
The last question in this topic looks at that last rule in more detail.