The Object class: every class's parent
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)You print a new object and see something like Student@1b6d3586, and you never wrote a toString(). Where did that method come from?
Object: the root of every class
The Object class (java.lang.Object) is the root class of Java: every class extends it, directly or through its parents. It gives every object common methods such as toString(), equals(), hashCode() and getClass().
You write class Pen {} with no extends, yet a Pen can call toString(). Java adds extends Object for you, and a class that extends another reaches Object through its parents.
Example 1 · Object sits at the top of every chain
class Person { String name;
Person(String name) { this.name = name; }}
class Student extends Person { int roll;
Student(String name, int roll) { super(name); this.roll = roll; }}
public class ChainDemo { public static void main(String[] args) { Student s = new Student("Aarav", 12); System.out.println(s.getClass().getSimpleName()); System.out.println(s.getClass().getSuperclass().getSimpleName()); System.out.println(s.getClass().getSuperclass().getSuperclass().getName()); }}Student Person java.lang.Object
What this code does
StudentextendsPerson, andPersonhas noextends, so Java made it extendObject.getSuperclass()moves one step up the chain each time; the top isjava.lang.Object.
Object lives in the package java.lang, like String, so it needs no import. It is the only class with no parent. The is-a idea from The extends keyword (opens in a new tab) simply goes one level higher: a Student is a Person, and a Person is an Object.
What every object gets from Object
An empty class still has methods, because it inherits them from Object. Four of them matter in this module: toString(), equals(), hashCode() and getClass().
Example 2 · An empty class still has methods
class Pen {}
public class EmptyClassDemo { public static void main(String[] args) { Pen p = new Pen(); Pen q = new Pen(); System.out.println(p.toString()); System.out.println(p.hashCode()); System.out.println(p.getClass().getName()); System.out.println(p.equals(p)); System.out.println(p.equals(q)); }}Pen@76ed5528 1995265320 Pen true false
What this code does
Pendeclares nothing, yet all four calls compile: they are inherited fromObject.- The number after
@and thehashCode()value depend on the computer and the run, so your first two lines will differ. - By default
equalsis true only for the same object, sop.equals(q)isfalseeven though both pens look the same.
What each one does until a class overrides it:
toString()returns text such asPen@76ed5528: the class name,@and the hash code in hexadecimal.equals(Object obj)istrueonly for the very same object.hashCode()returns anintfor the object, which Java uses to find objects fast.getClass()tells you the real class of the object; it cannot be overridden.
Object has a few more methods: clone() (see clone() and Cloneable (opens in a new tab)) and wait() / notify() for threads, which you can ignore for now.An Object reference can hold any object
A parent reference can point to a child object, as in Upcasting (opens in a new tab). Every class is a child of Object, so an Object variable or an Object[] can hold any object at all.
Example 3 · One Object array, many kinds of objects
class Student { String name;
Student(String name) { this.name = name; }}
public class ObjectArrayDemo { public static void main(String[] args) { Object[] bag = new Object[4]; bag[0] = new Student("Priya"); bag[1] = "Hello"; bag[2] = new int[] {90, 85}; bag[3] = new StringBuilder("UPI");
for (int i = 0; i < bag.length; i++) { System.out.println(i + ": " + bag[i].getClass().getSimpleName()); } }}0: Student 1: String 2: int[] 3: StringBuilder
What this code does
- Every object is an
Object, so oneObject[]can store a Student, a String, an array and a StringBuilder. - Each element is seen through an
Objectreference, yetgetClass()still reports the real class of each object.
Example 4 · Mistake: calling a Student method through Object
class Student { String name;
Student(String name) { this.name = name; }
String getName() { return name; }}
public class ObjectRefErrorDemo { public static void main(String[] args) { Object o = new Student("Kavya"); System.out.println(o.getClass().getSimpleName()); System.out.println(o.getName()); }}ObjectRefErrorDemo.java:17: error: cannot find symbol
System.out.println(o.getName());
^
symbol: method getName()
location: variable o of type Object
1 errorWhat this code does
- The object is a Student, but the reference type is
Object, andObjecthas nogetName()method. - The compiler checks the reference type only. Fix: declare
Student o = new Student("Kavya");(or cast, which the References, Casting & Immutability module covers).
The rule from Polymorphism still holds: the reference type decides what you may call, and the object decides which version runs. Through Object o only Object methods compile; if the class overrides one of them, its own version runs. Getting the Student back needs a cast, which Downcasting (opens in a new tab) covers.
Fix the error
Fix the Object reference
Read the error, then pick the line that fixes it.
Round 1 of 2
Print the phone's model. The object really is a Phone.
Error
PhoneDemo.java:9: error: cannot find symbol symbol: variable model location: variable o of type Object
getClass(): the real class of an object
getClass() is the Object method that returns the run-time class of an object: the class used with new, not the type of the reference. getSimpleName() on the result gives the short name, getName() the full name with its package.
With Person p = new Student(); the reference type is Person, but the object is a Student. getClass() looks at the object, never at the variable.
Example 5 · getClass() reports the object, not the variable
class Person {}
class Student extends Person {}
public class GetClassDemo { public static void main(String[] args) { Person p = new Student(); Object other = new Student(); Object plain = new Person();
System.out.println(p.getClass().getSimpleName()); System.out.println("Aarav".getClass().getName()); System.out.println(p.getClass().getSuperclass().getSimpleName()); System.out.println(p.getClass() == other.getClass()); System.out.println(p.getClass() == plain.getClass()); }}Student java.lang.String Person true false
What this code does
pis aPersonvariable, butgetClass()reportsStudent, the class used withnew.getName()gives the full name with the package (java.lang.String);getSuperclass()moves one step up.- Two
Studentobjects give the same class, so==on their classes istrue; aStudentand aPersongivefalse.
All objects of one class share one class object, so a.getClass() == b.getClass() is true exactly when both objects belong to the same class. Write your own equals() (opens in a new tab) uses this check.
getSuperclass() on the result gives the parent class, so you can walk up a chain all the way to Object.Next step
Check your understanding
12 quick questions