🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The Object class in the java.lang package is the root of the class hierarchy. Every class in Java inherits from this class, either directly or indirectly. This means every class has access to the methods provided by the Object class. Understanding these methods is fundamental to mastering Java.
Object Class Methods
Here are the methods we will cover:
protected Object clone()boolean equals(Object obj)protected void finalize()Class<?> getClass()int hashCode()void notify()void notifyAll()void wait()String toString()
1. protected Object clone()
The clone() method creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will also be true.
Example
class Person implements Cloneable {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person();
person1.setFirstName("Ramesh");
person1.setLastName("Fadatare");
Person person2 = (Person) person1.clone();
System.out.println(person1);
System.out.println(person2);
}
}
Output:
Person [firstName=Ramesh, lastName=Fadatare]
Person [firstName=Ramesh, lastName=Fadatare]
2. boolean equals(Object obj)
The equals(Object obj) method indicates whether some other object is "equal to" this one.
Example
class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
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 (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
public static void main(String[] args) {
Person person1 = new Person();
person1.setFirstName("Ramesh");
person1.setLastName("Fadatare");
Person person2 = new Person();
person2.setFirstName("Ramesh");
person2.setLastName("Fadatare");
System.out.println(person1.equals(person2));
}
}
Output:
true
3. protected void finalize() - deprecated
The finalize() method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Example
class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
protected void finalize() throws Throwable {
System.out.println("Person object is being garbage collected");
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");
person = null;
System.gc(); // Requesting JVM to run Garbage Collector
}
}
Output:
Person object is being garbage collected
4. Class<?> getClass()
The getClass() method returns the runtime class of an object.
Example
class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.getClass());
}
}
Output:
class Person
5. int hashCode()
The hashCode() method returns a hash code value for the object.
Example
class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
public static void main(String[] args) {
Person person1 = new Person();
person1.setFirstName("Ramesh");
person1.setLastName("Fadatare");
Person person2 = new Person();
person2.setFirstName("Ramesh");
person2.setLastName("Fadatare");
System.out.println(person1.hashCode());
System.out.println(person2.hashCode());
}
}
Output:
-1066062211
-1066062211
6. void notify(), 7. void notifyAll(), and 8. void wait()
These methods are used for thread synchronization.
Example
import java.util.LinkedList;
import java.util.List;
class ObjectClassNotifyNotifyAllAndWaitExample {
private final List<String> synchedList = new LinkedList<>();
public String removeElement() throws InterruptedException {
synchronized (synchedList) {
while (synchedList.isEmpty()) {
System.out.println("List is empty...");
synchedList.wait();
System.out.println("Waiting...");
}
return synchedList.remove(0);
}
}
public void addElement(String element) {
System.out.println("Opening...");
synchronized (synchedList) {
synchedList.add(element);
System.out.println("New Element added: '" + element + "'");
synchedList.notifyAll();
System.out.println("notifyAll called!");
}
System.out.println("Closing in AddElement method...");
}
public static void main(String[] args) {
final ObjectClassNotifyNotifyAllAndWaitExample demo = new ObjectClassNotifyNotifyAllAndWaitExample();
Runnable runA = () -> {
try {
String item = demo.removeElement();
System.out.println("" + item);
} catch (InterruptedException ix) {
System.out.println("Interrupted Exception!");
} catch (Exception x) {
System.out.println("Exception thrown.");
}
};
Runnable runB = () -> demo.addElement("Hello!");
try {
Thread threadA1 = new Thread(runA, "A");
threadA1.start();
Thread.sleep(500);
Thread threadA2 = new Thread(runA, "B");
threadA2.start();
Thread.sleep(500);
Thread threadB = new Thread(runB, "C");
threadB.start();
Thread.sleep(1000);
threadA1.interrupt();
thread
A2.interrupt();
} catch (InterruptedException x) {
x.printStackTrace();
}
}
}
Output:
List is empty...
List is empty...
Opening...
New Element added:'Hello!'
notifyAll called!
Waiting...
Closing in AddElement method...
Hello!
Waiting...
List is empty...
Interrupted Exception!
9. String toString()
The toString() method returns a string representation of the object.
Example
class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");
System.out.println(person.toString());
}
}
Output:
Person [firstName=Ramesh, lastName=Fadatare]
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Nicely explained each Object class method with examples. keep posting such useful stuff.
ReplyDelete“ Let's discuss one more example using the Closable interface and clone() method together.
ReplyDeleteFirst, create a Person class which implements a Closable interface.”
should be “Cloneable” not “Closable”