Java - Object Class: the Default Superclass

Introduction

If a class does not specify a superclass in its class declaration, it inherits from the java.lang.Object class.

For example, the following two class declarations for class P are the same:

"extends Object" is implicitly added for class P

public class P {
        // Code for class P goes here
}

"extends Object" is explicitly added for class P

public class P extends Object {
        // Code for class P goes here
}

Example

Consider the following snippet of code:

Employee emp = new Employee();
int hc = emp.hashCode();
String str = emp.toString();

The Object class declares the hashCode() and toString() methods.

Because the Employee class is implicitly a subclass of the Object class, it can use these methods.

Demo

class Employee {
  private String name = "Unknown";

  public void setName(String name) {
    this.name = name;
  }//from w w  w.ja  v  a 2s  . c  o m

  public String getName() {
    return name;
  }
}

public class Main {
  public static void main(String[] args) {
    Employee emp = new Employee();
    int hashCode = emp.hashCode();
    String str = emp.toString();
    System.out.println(hashCode);
    System.out.println(str);

  }
}

Result

Related Topic