The `Object` Class in Java
In Java, the Object
class is the root of the class hierarchy. Every class in Java is a subclass of Object
, either directly or indirectly. The Object
class defines the basic methods and properties that are inherited by all objects in Java.
The Object
class is located in the java.lang
package and is automatically imported into all Java programs. It contains a number of methods that are common to all objects in Java, such as toString
, equals
, and hashCode
.
Here is an example of how the Object
class is used in Java:
public class Person extends Object {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
In this example, the Person
class extends the Object
class and overrides the toString
and equals
methods. The toString
method is used to convert an object to a string representation, and the equals
method is used to compare the equality of two objects.
Here is an example of how the Person
class can be used:
Person p1 = new Person("John", 30);
Person p2 = new Person("John", 30);
System.out.println(p1.toString()); // prints "Person [name=John, age=30]"
System.out.println(p1.equals(p2)); // prints "true"
The Object
class also defines several other methods, such as hashCode
, clone
, and finalize
, which can be overridden by subclasses to provide custom behavior.