Skip to main content

Command Palette

Search for a command to run...

Object class in java

Published
•8 min read•View as Markdown

Sure! Let’s go in-depth on the Object class in Java, which is the root of the class hierarchy. Every class in Java directly or indirectly inherits from java.lang.Object. Understanding this is crucial for automation testers because methods like equals(), hashCode(), and toString() are often overridden in test frameworks and POM models.


Java Object Class – Detailed Overview

1. Introduction

  • Object class is part of java.lang package.

  • All Java classes inherit from Object if they don’t explicitly extend another class.

  • Provides basic methods for all objects, such as cloning, comparison, string representation, and synchronization support.


2. Important Methods in Object Class

MethodDescriptionExample / Usage
clone()Creates and returns a copy of the object. Supports shallow copy unless overridden for deep copy.Car c2 = (Car)c1.clone();
equals(Object obj)Compares object content for equality. Default compares references. Often overridden.c1.equals(c2)
hashCode()Returns integer hash code of object. Must be overridden if equals() is overridden.int code = c1.hashCode();
toString()Returns string representation of object. Default: ClassName@HashCode. Often overridden for readable info.System.out.println(c1.toString());
getClass()Returns runtime class of object.c1.getClass().getName();
finalize()Called by garbage collector before object destruction. Deprecated in Java 9+.Cleanup resources before GC.
notify()Wakes up a single thread waiting on this object.Thread synchronization.
notifyAll()Wakes up all threads waiting on this object.Thread synchronization.
wait()Causes current thread to wait until notified.Thread synchronization.
wait(long timeout)Waits for a maximum time or until notified.Thread synchronization.
wait(long timeout, int nanos)Waits with finer granularity.Thread synchronization.

3. Key Characteristics

  1. Root Class – All classes inherit from Object directly or indirectly.

  2. Polymorphic Methods – Methods like toString(), equals(), and hashCode() can be overridden.

  3. Thread Support – Provides wait(), notify(), notifyAll() for thread synchronization.

  4. Cloning Support – Implement Cloneable interface to allow clone().

  5. Garbage Collection Support – finalize() is called by GC (rarely used today).


4. Overriding Object Methods (Common in Automation)

Example – Override toString()

class Product {
    private String name;
    private int qty;

    public Product(String name, int qty) {
        this.name = name;
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Product{name='" + name + "', qty=" + qty + "}";
    }
}

public class TestObject {
    public static void main(String[] args) {
        Product p = new Product("Laptop", 10);
        System.out.println(p); // Output: Product{name='Laptop', qty=10}
    }
}

Example – Override equals() and hashCode()

class Product {
    private String name;
    private int qty;

    public Product(String name, int qty) {
        this.name = name;
        this.qty = qty;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if(obj == null || getClass() != obj.getClass()) return false;
        Product other = (Product) obj;
        return qty == other.qty && name.equals(other.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode() + qty;
    }
}

5. Usage in Automation Testing

  • toString() → Helpful for logging WebElement or Product info.

  • equals() → Used in assertions to compare actual vs expected objects.

  • hashCode() → Useful for HashMap/HashSet collections in test data.

  • wait() / notify() → Thread synchronization in parallel Selenium tests.


6. Summary

  • Every Java class inherits Object.

  • Provides essential methods for comparison, representation, cloning, and synchronization.

  • Overriding equals(), hashCode(), toString() is common in automation projects.

  • Useful in Page Object Model, test data validation, reporting, and parallel test execution.


If you want, I can also create a diagram showing all Object class methods, inheritance, and common overrides, which is very helpful for automation interviews.

Do you want me to make that diagram?

You said:

difrences

ChatGPT said:

Perfect 👌 — let’s go through the important differences related to the Object class that interviewers often ask automation testers and Java developers.

Here are the key comparison tables:


🧩 1. == vs equals()

Feature== Operatorequals() Method
TypeOperatorMethod (from Object class)
ComparisonCompares references (memory address)Compares content/data (if overridden)
Applicable toPrimitives & ObjectsObjects only
Default behaviorReturns true if both references point to same objectSame as == unless overridden
Common usageComparing primitive valuesComparing actual object data (like strings, products)
Example"A" == "A" → true"A".equals("A") → true

⚙️ 2. hashCode() vs equals()

Featureequals()hashCode()
PurposeChecks logical equality between objectsReturns integer hash value for object
RelationshipIf two objects are equal → must have same hashCodeSame hashCode ≠ objects are equal
Used inComparisons (e.g., assertions, object equality)Collections (HashMap, HashSet, Hashtable)
OverridingMust override both togetherAlways override if you override equals()
Examplep1.equals(p2)p1.hashCode() == p2.hashCode()

💬 3. toString() vs getClass()

FeaturetoString()getClass()
PurposeReturns string representation of objectReturns runtime class info
Default OutputClassName@HashCodeclass package.ClassName
Common UseLogging, debugging, reportingReflection, debugging
OverridableYes (commonly overridden)No (final method)
Examplep.toString() → Product{name='Laptop', qty=10}p.getClass().getName() → com.demo.Product

🔁 4. clone() vs new

Featureclone()new keyword
PurposeCopies an existing objectCreates a new object
InitializationCopies fields of existing objectCalls constructor
DependencyRequires implementing CloneableNo interface needed
TypeShallow copy by defaultFully new instance
ExampleProduct p2 = (Product)p1.clone();Product p2 = new Product();

🧵 5. wait() vs sleep()

Featurewait()sleep()
Defined InObject classThread class
Lock BehaviorReleases lock while waitingDoes not release lock
Used ForInter-thread communicationPausing execution temporarily
Requires synchronizedYesNo
ThrowsInterruptedExceptionInterruptedException
Exampleobj.wait(1000);Thread.sleep(1000);

🧠 6. notify() vs notifyAll()

Featurenotify()notifyAll()
PurposeWakes up one thread waiting on objectWakes up all threads waiting on object
EfficiencyFaster but less fairSlower but fair to all
When to useWhen only one thread needs to proceedWhen all waiting threads can continue
Exampleobj.notify();obj.notifyAll();

✅ Summary

MethodCategoryCommon Use in Automation
equals() / hashCode()ComparisonVerify test data or page object equality
toString()RepresentationLogging or reporting object details
clone()CopyingReuse or duplicate test data
wait()/notify()Thread controlSynchronize multi-threaded tests
getClass()ReflectionLogging class info dynamically

Would you like me to make one visual table or diagram summarizing all these Object class differences (for quick interview revision)?

You said:

ok

ChatGPT said:

Here’s a visual-style summary table of all the important Object class method differences — perfect for quick interview revision 📘👇


🧩 Java Object Class – Key Differences Summary

CategoryMethod/OperatorPurposeDefault BehaviorOverridableUsed In
Equality==Compares references (memory)Same reference → true❌Primitives / Object reference check
equals()Compares content/logical equalitySame as == unless overridden✅Comparing object data (e.g., strings, products)
HashinghashCode()Returns integer hash of objectUnique per object (by address)✅Collections (HashMap, HashSet)
RepresentationtoString()Returns string representationClassName@HashCode✅Logging, debugging
Type InfogetClass()Returns runtime classAlways gives class type❌ (final)Reflection, reporting
Copyingclone()Creates shallow copyShallow copy, must implement Cloneable✅Object duplication
Finalizationfinalize()Cleanup before GCCalled before garbage collection✅ (Deprecated)Resource cleanup (rare now)
Thread Controlwait()Pauses thread, releases lockWaits until notify()❌Thread sync (with synchronized)
notify()Wakes up one waiting threadNotifies one thread❌Inter-thread communication
notifyAll()Wakes up all waiting threadsNotifies all❌Inter-thread communication

⚖️ Key Comparison Tables

ComparisonDifference
== vs equals()== → compares references; equals() → compares content
equals() vs hashCode()Both must be overridden together for consistency
toString() vs getClass()toString() → readable output; getClass() → class metadata
clone() vs newclone() copies existing object; new creates fresh instance
wait() vs sleep()wait() releases lock; sleep() does not
notify() vs notifyAll()One thread vs all threads awakened

💡 Interview Tips

  • Always override equals() and hashCode() together.

  • Override toString() in model/POM classes for readable logs.

  • Avoid finalize() — deprecated after Java 9.

  • clone() requires Cloneable interface, else CloneNotSupportedException.

  • wait(), notify(), notifyAll() must be used inside a synchronized block.

More from this blog

SS-JAVA

23 posts