Modern software architecture is often broken. Slow delivery
leads to missed opportunities, innovation is stalled due to
architectural complexities, and engineering resources are
exceedingly expensive.
Orkes is the leading workflow orchestration platform
built to enable teams to transform the way they develop, connect,
and deploy applications, microservices, AI agents, and more.
With Orkes Conductor managed through Orkes Cloud, developers can
focus on building mission critical applications without worrying
about infrastructure maintenance to meet goals and, simply put,
taking new products live faster and reducing total cost of
ownership.
Modern software architecture is often broken. Slow delivery
leads to missed opportunities, innovation is stalled due to
architectural complexities, and engineering resources are
exceedingly expensive.
Orkes is the leading workflow orchestration platform
built to enable teams to transform the way they develop, connect,
and deploy applications, microservices, AI agents, and more.
With Orkes Conductor managed through Orkes Cloud, developers can
focus on building mission critical applications without worrying
about infrastructure maintenance to meet goals and, simply put,
taking new products live faster and reducing total cost of
ownership.
eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
Handling concurrency in an application can be a tricky process
with many potential pitfalls. A solid grasp of the
fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with
our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring
WebFlux module, which has been improved upon ever since. Get
started with the Reactor project basics and reactive programming
in Spring Boot:
Since its introduction in Java 8, the Stream API has become a
staple of Java development. The basic operations like iterating,
filtering, mapping sequences of elements are deceptively simple to
use.
But these can also be overused and fall into some common
pitfalls.
To get a better understanding on how Streams work and how
to combine them with other language features, check out our guide
to Java Streams:
Yes, Spring Security can be complex, from the more advanced
functionality within the Core to the deep OAuth support in the
framework.
I built the security material as two full courses - Core and
OAuth, to get practical with these more complex scenarios. We
explore when and how to use each feature and code through it on
the backing project.
Browser testing is essential if you have a website or web
applications that users interact with. Manual testing can be very
helpful to an extent, but given the multiple browsers available,
not to mention versions and operating system, testing everything
manually becomes time-consuming and repetitive.
To help automate this process, Selenium is a popular
choice for developers, as an open-source tool with a large and
active community. What's more, we can further scale our automation
testing by running on theLambdaTest cloud-based testing
platform.
Read more through our step-by-step tutorial on how to set up
Selenium tests with Java and run them on LambdaTest:
Modern software architecture is often broken. Slow delivery
leads to missed opportunities, innovation is stalled due to
architectural complexities, and engineering resources are
exceedingly expensive.
Orkes is the leading workflow orchestration platform
built to enable teams to transform the way they develop, connect,
and deploy applications, microservices, AI agents, and more.
With Orkes Conductor managed through Orkes Cloud, developers can
focus on building mission critical applications without worrying
about infrastructure maintenance to meet goals and, simply put,
taking new products live faster and reducing total cost of
ownership.
Refactor Java code safely — and automatically — with
OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to
put off. That’s where OpenRewrite comes in. The open-source
framework for large-scale, automated code transformations helps
teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at
Moderne run live, hands-on training sessions — one for newcomers
and one for experienced users. You’ll see how recipes work, how to
apply them across projects, and how to modernize code with
confidence.
Join the next session,
bring your questions, and learn how to automate the kind of work
that usually eats your sprint time.
1. Overview
The Object class is the root of the class hierarchy in Java. Every class in Java is either a direct or indirect subclass of Object. Therefore, all objects, including arrays, inherit implementations of the methods of the Object class and may override them if desired.
In this quick, high-level guide, we’ll discuss the Object class in detail.
2. Importance of the Object Class
The Object class is important for several reasons:
Universal Base Class: It provides a common type for all objects and is why a variable of type Object can hold a reference to any object. Suppose we have a Car class. Then, we could write: Object obj = new Car();.
Polymorphism: The methods defined in Object, such as equals and toString, establish a contract that all objects must fulfill, allowing for consistent interaction with objects of various types.
Collection Framework: Many classes in the Java Collections Framework, like ArrayList and HashMap, are designed to work with Object references, relying heavily on the correct implementation of equals() and hashCode().
3. Key Methods of the Object Class
The Object class provides several methods that all other classes inherit:
Method
Purpose
Notes
equals(Object obj)
Indicates whether some other object is “equal to” this one.
Generally, we should override this method to provide a meaningful comparison of the objects’ state (content) rather than just memory addresses.
hashCode()
Returns a hash code value for the object.
It’s critical to override hashCode() whenever we override equals() to ensure that two equal objects have the same hash code, which is essential for collections like HashMap and HashSet.
toString()
Returns a string representation of the object.
The default implementation returns a string consisting of the class name, the ‘@’ sign, and the unsigned hexadecimal representation of the object’s hash code. We should override it to describe the object’s contents.
getClass()
Returns the runtime class of this Object.
We can use the returned Class object for reflection – examining or modifying the behavior of a class at runtime.
clone()
Creates and returns a copy of this object.
Requires the class to implement the Cloneable interface. The default implementation performs a shallow copy. We must typically override it and handle the CloneNotSupportedException.
wait(), notify(), notifyAll()
Used for inter-thread communication and synchronization.
These methods are generally invoked on a monitor (lock) associated with the object and are used within synchronized code blocks or methods.
finalize()
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
This method is deprecated and shouldn’t be relied upon for resource cleanup. Modern Java practices prefer using try-with-resources or other explicit cleanup mechanisms.
4. Example Class
Let’s use a simple Car class that overrides several of the standard Object methods. To properly support clone(), the Car class must implement the marker interface Cloneable and override the protected clone() method:
public class Car implements Cloneable {
private String make;
private int year;
public Car(String make, int year) {
this.make = make;
this.year = year;
}
public String getMake() {
return make;
}
public int getYear() {
return year;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Car car = (Car) obj;
return year == car.year && Objects.equals(make, car.make);
}
@Override
public int hashCode() {
return Objects.hash(make, year);
}
@Override
public String toString() {
return "Car{"
+ "make='" + make + '\''
+ ", year=" + year
+ '}';
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Accordingly, the class uses standard implementations for equals(), hashCode(), and toString(). Further, it overrides the protected clone() method from Object to perform a shallow copy. This is the standard pattern when implementing the Cloneable marker interface.
5. Exploring Methods
Let’s use JUnit tests to demonstrate how these methods behave.
5.1. equals(Object obj)
First, we verify that the equals() method satisfies the reflexive, symmetric, transitive, and consistent properties:
@Test
void givenACarObject_whenTestingObjectEqualsItself_thenEqualsReflexive() {
Car car1 = new Car("Honda", 2020);
assertTrue(car1.equals(car1));
}
@Test
void givenTwoCarObjects_whenTestingSymmetric_thenEqualsSymmetric() {
Car car1 = new Car("Honda", 2020);
Car car2 = new Car("Honda", 2020);
assertTrue(car1.equals(car2));
assertTrue(car2.equals(car1);
}
@Test
void givenThreeCarObjects_whenTestingTransitive_thenEqualsTransitive() {
Car car1 = new Car("Honda", 2020);
Car car2 = new Car("Honda", 2020);
Car car3 = new Car("Honda", 2020);
assertTrue(car1.equals(car2));
assertTrue(car2.equals(car3));
assertTrue(car1.equals(car3));
}
@Test
void givenTwoDifferentCarObjects_whenComparingWithEquals_thenEqualsReturnsFalse() {
Car car1 = new Car("Honda", 2020);
Car car2 = new Car("Toyota", 2020);
assertFalse(car1.equals(car2));
}
@Test
void givenANonNullCarObject_whenTestingAgainstNull_thenEqualsReturnsFalse() {
Car car1 = new Car("Honda", 2020);
assertFalse(car1.equals(null));
}
As we can see from these examples, “reflexive” means that an object equals itself. Furthermore, “symmetric” means that if car1.equals(car2) is true, then car2.equals(car1) is also true. Additionally, “transitive” means that if a==b and b==c, then a==c. Next, we verified the consistency that objects with different states are unequal. Finally, we see that equals() returns false for a null input.
5.2. hashCode()
The hashCode() method ensures that if two objects are equal according to the equals() method, then calling hashCode() on each object produces the same integer result; equal objects MUST have equal hash codes:
@Test
void givenTwoEqualCarObjects_whenComparingHashCodes_thenReturnsEqualHashCodes() {
Car car1 = new Car("Honda", 2020);
Car car2 = new Car("Honda", 2020);
assertEquals(car1.hashCode(), car2.hashCode());
}
@Test
void givenACarObject_whenTestingHashCodeConsistency_thenReturnsSameHashCodeAcrossMultipleCalls() {
Car car = new Car("Honda", 2020);
int initialHash = car.hashCode();
assertEquals(initialHash, car.hashCode());
}
5.3. toString()
The toString() method should return a string consisting of a concise and informative representation of the object’s content. Let’s confirm that it returns the expected string with a quick test:
@Test
void givenACarObject_whenTestingToString_thenReturnsExpectedString() {
Car car = new Car("Tesla", 2023);
String expected = "Car{make='Tesla', year=2023}";
assertEquals(expected, car.toString());
}
5.4. getClass()
Let’s verify that the getClass() method returns the runtime type of the object:
@Test
void givenACarObject_whenTestingGetClass_thenReturnsCarClass() {
Car car = new Car("Ford", 2015);
assertEquals(Car.class, car.getClass());
}
Next, we test that clone() creates a copy that’s a new object (at a different memory address) but equal in content:
@Test
void givenACarObject_whenTestingClone_thenCloneSuccess throws CloneNotSupportedException {
Car original = new Car("Honda", 2020);
Car cloned = (Car) original.clone();
assertNotSame(original, cloned);
assertEquals(original, cloned);
assertEquals(original.getMake(), cloned.getMake());
assertEquals(original.getYear(), cloned.getYear());
}
Note that because the return type of clone() is Object, we have to cast the return value to the Car class.
5.6. wait(), notify(), and notifyAll()
The wait(), notify(), and notifyAll() methods are used for thread synchronization in a multi-threaded environment. We need to avoid concurrency issues by preventing multiple threads from trying to modify the same Object instance simultaneously.
5.7. finalize()
The finalize() method is called before the garbage collection for a particular object. Note that this method was deprecated in Java 9 and may be removed in a future Java version.
6. Conclusion
In this article, we explored the Object class in Java in great detail. We started by explaining why Object is important and then explored its methods. Finally, we used an example class called Car to demonstrate the behavior of these methods.
As always, the full code for the examples is available over on GitHub.
Baeldung Pro – NPI EA (cat = Baeldung)
Baeldung Pro comes with both absolutely No-Ads as well as
finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go
up and stay at $33/year.
Partner – Orkes – NPI EA (cat = Spring)
Modern software architecture is often broken. Slow delivery
leads to missed opportunities, innovation is stalled due to
architectural complexities, and engineering resources are
exceedingly expensive.
Orkes is the leading workflow orchestration platform
built to enable teams to transform the way they develop, connect,
and deploy applications, microservices, AI agents, and more.
With Orkes Conductor managed through Orkes Cloud, developers can
focus on building mission critical applications without worrying
about infrastructure maintenance to meet goals and, simply put,
taking new products live faster and reducing total cost of
ownership.
Modern software architecture is often broken. Slow delivery
leads to missed opportunities, innovation is stalled due to
architectural complexities, and engineering resources are
exceedingly expensive.
Orkes is the leading workflow orchestration platform
built to enable teams to transform the way they develop, connect,
and deploy applications, microservices, AI agents, and more.
With Orkes Conductor managed through Orkes Cloud, developers can
focus on building mission critical applications without worrying
about infrastructure maintenance to meet goals and, simply put,
taking new products live faster and reducing total cost of
ownership.
eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
The Apache HTTP Client is a very robust library, suitable
for both simple and advanced use cases when testing HTTP
endpoints. Check out our guide covering basic request and
response handling, as well as security, cookies, timeouts, and
more:
eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
Handling concurrency in an application can be a tricky process
with many potential pitfalls. A solid grasp of the
fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with
our Java Concurrency guide:
Since its introduction in Java 8, the Stream API has become a
staple of Java development. The basic operations like iterating,
filtering, mapping sequences of elements are deceptively simple to
use.
But these can also be overused and fall into some common
pitfalls.
To get a better understanding on how Streams work and how
to combine them with other language features, check out our guide
to Java Streams:
Modern Java teams move fast — but codebases
don’t always keep up. Frameworks change, dependencies drift, and
tech debt builds until it starts to drag on delivery. OpenRewrite
was built to fix that: an open-source refactoring engine that
automates repetitive code changes while keeping developer intent
intact.
The monthly training series, led by the creators and maintainers
of OpenRewrite at Moderne, walks through real-world migrations and
modernization patterns. Whether you’re new to recipes or ready to
write your own, you’ll learn practical ways to refactor safely and
at scale.