Object class - Notes by Shariq SP
Object Class in Java
The Object class is the root class in Java's class hierarchy. It is located in the java.lang package and serves as the superclass for all other classes in Java. Every class in Java directly or indirectly extends the Object class. The Object class provides several important methods that are inherited by all Java objects.
Methods of Object Class
- toString(): This method returns a string representation of the object. It is commonly overridden to provide a meaningful description of the object's state.
- equals(Object obj): The equals() method is used to compare the equality of two objects. By default, it checks for reference equality, but it is often overridden to compare the contents of objects.
- hashCode(): This method returns a hash code value for the object. It is used in hashing-based collections such as HashMap, HashSet, etc.
- getClass(): Returns the runtime class of an object. It returns an instance of Class extends Object> representing the runtime class of the object.
- clone(): The clone() method is used to create a copy of the object. It creates and returns a new object that is a copy of the original object.
- finalize(): This method is called by the garbage collector before an object is removed from memory. It can be overridden to perform cleanup operations.
Methods of the Object Class:
1. toString():
The toString() method returns a string representation of the object. By default, it returns a string consisting of the class name followed by the "@" character and the object's hashcode in hexadecimal format.
class MyClass {
int id;
String name;
public MyClass(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "MyClass [id=" + id + ", name=" + name + "]";
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass(1, "Example");
System.out.println(obj); // Output: MyClass [id=1, name=Example]
}
}
2. equals(Object obj):
The equals() method compares two objects for equality. By default, it compares the memory addresses of the objects. This method is often overridden to provide custom equality checks based on object properties.
class MyClass {
int id;
String name;
public MyClass(int id, String name) {
this.id = id;
this.name = name;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
MyClass myObj = (MyClass) obj;
return id == myObj.id && Objects.equals(name, myObj.name);
}
}
public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass(1, "Example");
MyClass obj2 = new MyClass(1, "Example");
System.out.println(obj1.equals(obj2)); // Output: true
}
}
3. hashCode():
The hashCode() method returns the hash code value for the object. By default, it returns the memory address of the object in integer format. It is used in conjunction with hash-based data structures like HashMap.
class MyClass {
int id;
String name;
public MyClass(int id, String name) {
this.id = id;
this.name = name;
}
public int hashCode() {
return Objects.hash(id, name);
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass(1, "Example");
System.out.println(obj.hashCode()); // Output: hash code value
}
}
4. getClass():
The getClass() method returns the runtime class of the object. It returns an instance of the Class class representing the runtime class of the object.
class MyClass {
// class definition
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
Class extends MyClass> objClass = obj.getClass();
System.out.println(objClass.getName()); // Output: MyClass
}
}
5. clone():
The clone() method creates and returns a copy of the object. The class of the object must implement the Cloneable interface, otherwise, it will throw a CloneNotSupportedException.
class MyClass implements Cloneable {
// class definition
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
try {
MyClass obj2 = (MyClass) obj1.clone();
// Perform operations with obj2
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
6. finalize():
The finalize() method is called by the garbage collector before reclaiming the memory occupied by the object. It can be overridden to perform cleanup operations, such as releasing system resources.
class MyClass {
// class definition
protected void finalize() {
// cleanup operations
}
}
public class Main {
public static void main(String[] args) {
// Code to create and use MyClass objects
}
}
7. notify(), notifyAll(), wait():
These methods are used for inter-thread communication and synchronization. They are typically used in conjunction with synchronized blocks to coordinate the execution of multiple threads.
notify() - Wakes up a single thread that is waiting on the object's monitor.
notifyAll() - Wakes up all threads that are waiting on the object's monitor.
wait() - Causes the current thread to wait until another thread notifies it or the specified timeout expires.
Interview Questions on Object Class
Interview Questions:
- What is the significance of the Object class in Java?
- What are some methods provided by the Object class?
- Explain the importance of the toString() method in the Object class.
- How does the equals() method work in the Object class?
- What is the default implementation of the hashCode() method in the Object class?
- Explain the concept of method overriding with respect to the Object class.
- Why is it recommended to override the hashCode() method when the equals() method is overridden?
- What is the significance of the getClass() method in the Object class?
- How does the finalize() method work in the Object class?
- Explain the clone() method in the Object class and its limitations.
Multiple Choice Questions (MCQs):
- Which of the following methods is defined in the Object class?
a) toString()
b) equals()
c) hashCode()
d) All of the above
Answer: d) All of the above - The finalize() method in the Object class is used for:
a) Memory allocation
b) Resource cleanup
c) Garbage collection
d) Exception handling
Answer: c) Garbage collection - Which method is used to obtain the class of an object in Java?
a) getClass()
b) getType()
c) getTypeOf()
d) classOf()
Answer: a) getClass() - What is the default implementation of the hashCode() method?
a) It returns the memory address of the object.
b) It returns a unique identifier for the object.
c) It returns the hash code value calculated based on the object's memory location.
d) It returns the hash code value calculated based on the object's state.
Answer: a) It returns the memory address of the object. - Which method is used to compare two objects for equality?
a) compare()
b) equals()
c) compareTo()
d) isEqual()
Answer: b) equals()