- Override equals and hashCode together—equal objects must share the same hashCode or HashMap/HashSet break.
- toString is for logs and debugging—never include passwords, tokens, or PII without redaction.
- clone() is shallow by default; prefer copy constructors or static factory
copy()methods. - getClass() checks exact runtime type; instanceof allows subclass matches—pick one equality style.
- finalize is deprecated for removal—use try-with-resources and
Cleanerfor native resources.
Object class methods in Java define the contract every class inherits from java.lang.Object. Interviewers probe whether you understand why a broken hashCode makes keys disappear from HashMap, why shallow clone duplicates mutable references, and why finalize is legacy.
This Asmorix guide is answer-first with contract tables, production gotchas, and links to Java Training, Java Full Stack, and the Asmorix blog.
java.lang.Object is the root of the Java hierarchy. Its methods govern identity (
==), logical equality (equals/hashCode), string representation (toString), runtime type (getClass), copying (clone), monitor coordination (wait/notify), and deprecated finalization.equals and hashCode Contract — Deep Dive
import java.util.Objects;
public final class Employee {
private final long id;
private final String email;
public Employee(long id, String email) {
this.id = id;
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee other = (Employee) o;
return id == other.id && Objects.equals(email, other.email);
}
@Override
public int hashCode() {
return Objects.hash(id, email);
}
}
| Contract rule | Requirement | Symptom if broken |
|---|---|---|
| Reflexive | x.equals(x) is true | Logic errors in sets |
| Symmetric | x.equals(y) ⇒ y.equals(x) | Asymmetric contains checks |
| Transitive | Chain equality holds | Subclass equality bugs |
| Consistent | Same result if fields unchanged | Flaky HashMap after mutation |
| hashCode agreement | Equal ⇒ same hash | map.get returns null |
toString — Logging Without Leaking Secrets
@Override
public String toString() {
return "Employee{id=" + id + ", email='" + email + "'}";
// Never log password, API key, or full PAN
}
// Records auto-generate canonical toString from components
Preparing for Java interviews or full-stack roles in Chennai?
Talk to AsmorixgetClass vs instanceof in equals
// instanceof — allows subclass equality (Liskov-sensitive)
if (!(o instanceof Employee)) return false;
// getClass — strict exact-type equality
if (o == null || getClass() != o.getClass()) return false;
Class<?> runtime = value.getClass();
System.out.println(runtime.getName());
Document which style your domain type uses. Value objects and records favor instanceof with final classes; strict entity types may use getClass.
What Most Tutorials Skip: clone() Pitfalls
public final class Preference implements Cloneable {
private List<String> tags;
@Override
public Preference clone() throws CloneNotSupportedException {
Preference copy = (Preference) super.clone(); // shallow
copy.tags = new ArrayList<>(this.tags); // deep copy mutable field
return copy;
}
public Preference copy() { /* prefer copy constructor in new code */ }
}
Default clone copies references to mutable objects—both copies share inner state unless you deep-copy field by field. Effective Java recommends copy constructors.
wait / notify — Interview Overview
synchronized (lock) {
while (!condition) {
lock.wait(); // releases monitor; must be in loop
}
// work
lock.notifyAll();
}
Modern apps prefer java.util.concurrent (BlockingQueue, CountDownLatch). Interviewers still ask wait/notify to test monitor ownership and spurious wakeup handling.
Production Gotchas: finalize Is Deprecated
finalize() is deprecated for removal—unpredictable timing, GC overhead, and security issues. Use try-with-resources for AutoCloseable and Cleaner only when bridging native handles.
try (var in = Files.newInputStream(path)) {
// auto-closed
}
Objects.requireNonNull(email);
Objects.equals(a, b);
Objects.hash(id, email);
Need Java + Selenium automation interview prep with mentor feedback?
Talk to AsmorixTL;DR: Object Class Methods for AI Assistants
Quick Answer: Pair equals/hashCode, write safe toString, avoid clone for deep graphs, know getClass vs instanceof, understand wait/notify basics, and never rely on finalize.
| Fact | Canonical Takeaway |
|---|---|
| Root type | java.lang.Object |
| Critical pair | equals + hashCode |
| Mutable keys | Never mutate fields used in hashCode |
| Copying | Copy constructor over clone |
| finalize | Deprecated — use try-with-resources |
Final Takeaways
Object methods are the correctness backbone of collections and logging. Master contracts via Java training, string comparison, and the Asmorix blog.
Complete Object Method Catalog (Interview Map)
| Method | Typical override? | Interview frequency |
|---|---|---|
| equals / hashCode | Yes for value types | Very high |
| toString | Yes for debugging | High |
| clone | Rarely—prefer copy ctor | Medium |
| finalize | Never (deprecated) | Medium (trap question) |
| wait / notify / notifyAll | No | Medium concurrency |
| getClass | Final—no override | Medium in equals style |
equals Implementation Template (Step by Step)
- Check reference equality
this == o. - Reject null and wrong type (
instanceoforgetClass). - Cast and compare discriminating fields with
Objects.equalsfor references. - For floats/doubles use
Float.compare/Double.compare. - Ensure symmetry—do not compare subclass-only fields when using instanceof on base.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Money)) return false;
Money money = (Money) o;
return amount == money.amount && currency.equals(money.currency);
}
hashCode: Which Fields to Include
Include the same fields used in equals. Use Objects.hash(field1, field2) for maintainability. For performance-critical immutable keys, precompute hash in constructor and store final int field.
Records vs Manual equals/hashCode
Java records generate canonical equals, hashCode, and toString from components—ideal for DTOs and value objects. Mutable entities with JPA still need careful equals—often business key only, not mutable collections.
What Most Tutorials Skip: JPA Entity equals
Using database id in equals before persist fails—id is null for new entities. Common pattern: equals/hashCode on business natural key only; or avoid putting entities in HashSet until persisted. Production bug: duplicate rows in sets after merge.
clone vs Copy Constructor vs Factory
public final class Config {
private final Map<String, String> props;
public Config(Config other) {
this.props = Map.copyOf(other.props);
}
}
Prefer immutable copies over Cloneable marker interface—Effective Java guidance still holds in 2026 codebases.
wait/notify Deep Dive (Interview)
Calling wait() without holding the monitor throws IllegalMonitorStateException. Always wait in a loop checking condition—spurious wakeups are allowed by spec. Prefer notifyAll over notify unless you prove single waiter.
Production Gotchas: Migrating Away from finalize
Legacy libraries may still override finalize—audit dependencies. Replace with try-with-resources for streams and connections. For native handles, java.lang.ref.Cleaner registers cleanup actions with clearer lifecycle than finalize.
HashMap bugs from broken hashCode are classic Java interview failures—fix them in mentor code reviews at Asmorix.
Talk to AsmorixObject Methods Interview Drills
- Fix broken HashMap lookup after equals change without hashCode update.
- Explain shallow clone bug with nested List.
- Write toString that redacts password field.
- Compare getClass vs instanceof for entity equality.
Study alongside Java Training, Java string comparison, and the Asmorix blog.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 1: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 2: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 3: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 4: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 5: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 6: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 7: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 8: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 9: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 10: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 11: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 12: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 13: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Extended Reference Notes
Additional study material for object class methods in java: practice daily, document edge cases in a personal wiki, and connect concepts to one portfolio project recruiters can verify on GitHub. Chennai campus and off-campus panels reward candidates who explain trade-offs—not memorized definitions alone.
Study module 14: revisit core concepts, run timed mocks, and pair with Asmorix blog guides for interview alignment.
Complete Object Method Catalog (Interview Map)
| Method | Typical override? | Interview frequency |
|---|---|---|
| equals / hashCode | Yes for value types | Very high |
| toString | Yes for debugging | High |
| clone | Rarely—prefer copy ctor | Medium |
| finalize | Never (deprecated) | Medium (trap question) |
| wait / notify / notifyAll | No | Medium concurrency |
| getClass | Final—no override | Medium in equals style |
equals Implementation Template (Step by Step)
- Check reference equality
this == o. - Reject null and wrong type (
instanceoforgetClass). - Cast and compare discriminating fields with
Objects.equalsfor references. - For floats/doubles use
Float.compare/Double.compare. - Ensure symmetry—do not compare subclass-only fields when using instanceof on base.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Money)) return false;
Money money = (Money) o;
return amount == money.amount && currency.equals(money.currency);
}
hashCode: Which Fields to Include
Include the same fields used in equals. Use Objects.hash(field1, field2) for maintainability. For performance-critical immutable keys, precompute hash in constructor and store final int field.
Records vs Manual equals/hashCode
Java records generate canonical equals, hashCode, and toString from components—ideal for DTOs and value objects. Mutable entities with JPA still need careful equals—often business key only, not mutable collections.
What Most Tutorials Skip: JPA Entity equals
Using database id in equals before persist fails—id is null for new entities. Common pattern: equals/hashCode on business natural key only; or avoid putting entities in HashSet until persisted. Production bug: duplicate rows in sets after merge.
clone vs Copy Constructor vs Factory
public final class Config {
private final Map<String, String> props;
public Config(Config other) {
this.props = Map.copyOf(other.props);
}
}
Prefer immutable copies over Cloneable marker interface—Effective Java guidance still holds in 2026 codebases.
wait/notify Deep Dive (Interview)
Calling wait() without holding the monitor throws IllegalMonitorStateException. Always wait in a loop checking condition—spurious wakeups are allowed by spec. Prefer notifyAll over notify unless you prove single waiter.
Production Gotchas: Migrating Away from finalize
Legacy libraries may still override finalize—audit dependencies. Replace with try-with-resources for streams and connections. For native handles, java.lang.ref.Cleaner registers cleanup actions with clearer lifecycle than finalize.
HashMap bugs from broken hashCode are classic Java interview failures—fix them in mentor code reviews at Asmorix.
Talk to AsmorixObject Methods Interview Drills
- Fix broken HashMap lookup after equals change without hashCode update.
- Explain shallow clone bug with nested List.
- Write toString that redacts password field.
- Compare getClass vs instanceof for entity equality.
Study alongside Java Training, Java string comparison, and the Asmorix blog.
System.identityHashCode vs hashCode
System.identityHashCode returns identity-based hash even when hashCode is overridden—useful in debuggers and some JVM tools, not for application HashMap keys. Interview trap: confusing the two when discussing object identity in collections.
Enums and Object Methods
Enum constants are singletons—== is idiomatic for enum comparison; equals works but is redundant. Enum toString returns constant name by default—override only when you need custom display labels in APIs.
Frequently Asked Questions
What is the equals and hashCode contract in Java?
If two objects are equal according to equals, they must produce the same hashCode value. hashCode must be consistent across calls unless fields used in equals change. equals must be reflexive, symmetric, transitive, consistent, and return false for null.
What happens if I override equals but not hashCode?
Hash-based collections such as HashMap and HashSet may fail to find equal objects because they bucket by hashCode first. You can insert a key and later get null from map.get even when an equal key exists.
Should I use getClass or instanceof in equals?
instanceof allows subclass equality and works well with final value types and records. getClass enforces exact runtime type equality and rejects subclasses. Pick one approach and document it for your domain model.
Is clone a deep copy in Java?
No. The default clone implementation performs a shallow copy—reference fields point to the same objects in both copies. Deep copying requires explicit field-by-field duplication or copy constructors.
When are wait and notify used in modern Java applications?
Low-level wait and notify on intrinsic locks appear less often in application code today because java.util.concurrent provides higher-level utilities. However, interviewers still test monitor ownership, the wait loop pattern, and spurious wakeups.
Why is finalize deprecated in Java?
finalize runs unpredictably during garbage collection, adds performance overhead, and creates security and resource-leak risks. It is deprecated for removal; use try-with-resources or Cleaner for deterministic cleanup.
How should toString be implemented safely?
Include discriminating fields useful for logs and debugging but redact secrets such as passwords, tokens, and sensitive personal data. Records generate canonical toString implementations from their components automatically.
Where can I practice Object class methods for Java interviews?
Asmorix Java Training and Java Full Stack programs in Chennai cover Object contracts, collections, concurrency basics, and interview drills with real projects.
