Object Class Methods
Every Java class automatically inherits from Object.
class Person {
}
is basically:
class Person extends Object {
}
Common Methods
1. equals()
Checks whether two objects are equal.
Person p1 = new Person();
Person p2 = new Person();
p1.equals(p2); // false
By default, it behaves like ==.
Override
equals()when you want to compare object values.
2. hashCode()
Returns a number (hash) representing the object.
p1.hashCode();
If you override
equals(), also overridehashCode().
3. toString()
Returns a string describing the object.
System.out.println(p1);
By default, you get something like:
Person@5acf9800
You can override it:
@Override
public String toString() {
return "Person";
}
4. getClass()
Tells you the object's actual class.
System.out.println(p1.getClass());
Output:
class Person
getClass()cannot be overridden.
5. clone()
Creates a copy of an object.
Person copy = (Person) p1.clone();
Requires
Cloneableand should be used carefully.
6. finalize()
Was intended for cleanup before garbage collection.
Do not use it. It is deprecated. Use
AutoCloseable/ try-with-resources instead.
Easy Summary
| Method | Purpose |
|---|---|
equals() |
Compare objects |
hashCode() |
Get hash value |
toString() |
Get object as text |
getClass() |
Get object's class |
clone() |
Copy object |
finalize() |
Old cleanup method — avoid |