top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Object Class in Java

Introduction

In the world of Java programming, the Object class holds a special place as it serves as the foundation for all Java classes. Understanding the Object class and its methods is crucial for every Java developer, as it allows for the effective implementation of various functionalities. In this article, we will explore the Object class in Java, its characteristics, methods, and how it relates to inheritance. By the end, you will have a solid understanding of the Object class and its significance in Java programming.

Overview

In Java, every class is derived from the Object in Java, whether explicitly or implicitly. The Object class resides in java.lang package, making it readily available to all Java programs. It serves as the parent class for all other classes, and by default, every class inherits the methods of the Object class. This allows objects to exhibit common behaviors and functionalities, making Java a truly object-oriented programming language.

Object Class in Java: Description and Characteristics

The Object class in Java provides a set of default methods and properties that are inherited by all other classes. Some of its characteristics include:

  • Universal Superclass: The Object class acts as the universal superclass for all other classes in Java. Any class that does not explicitly extend another class inherits the Object class by default.

  • Base for Polymorphism: Polymorphism, a fundamental concept in object-oriented programming, relies on the Object class. It allows objects of different classes to be treated as objects of the Object class, enabling dynamic method dispatch and method overriding.

  • toString() Method: The Object class defines a toString() method, which provides a string representation of an object. It is commonly used for debugging purposes and can be overridden in derived classes to return customized representations.

Methods and Properties of the Object Class

The Object class method in Java provides several methods and properties that can be utilized by all classes. Let's take a closer look at some commonly used methods:

  1. equals(Object obj): The equals() method compares two objects for equality. By default, it checks if the references of the two objects point to the same memory location. However, it can be overridden in derived classes to provide custom equality checks based on object attributes.

String text1 = "Hello";
String text2 = "Hello";

System.out.println(text1.equals(text2)); // true

Output: 

true

The equals() method is used to compare two String objects (text1 and text2) based on their contents. The result is true since both strings have the same content ("Hello").

  1. hashCode(): The hashCode() method returns a unique integer value associated with an object. It is primarily used in hashing-based data structures like HashMap and HashSet. When overriding the equals() method, it is recommended to override the hashCode() method as well to maintain consistency. Example:

String text = "Hello";

System.out.println(text.hashCode());  

The hashCode() method is called on the String object text to generate a unique hash code value based on its content. The output -907987551 is the hash code value calculated for the string "Hello".

  1. toString(): The toString() method returns a string representation of an object. It is commonly used for displaying meaningful information about an object. By default, it returns the class name followed by the hash code of the object, but it can be overridden to provide a more descriptive representation.

String text = "Hello";

System.out.println(text.toString()); 

The toString() method is called on the String object text to return a string representation of the object. In this case, the output is the same as the original string, "Hello".

  1. clone(): The clone() method creates a shallow copy of an object. It allows you to duplicate an object with its current state. Implementing the Cloneable interface is necessary for using this method.

String text = "Hello";
String clonedText = text.clone();

System.out.println(clonedText); //

 Output:

 "Hello"

The clone() method is not available for the String class because String objects are immutable (cannot be changed). Therefore, this example will result in a compilation error.

  1. getClass(): The getClass() method returns the runtime class of an object. It provides information about the class to which the object belongs. It is often used for reflection and obtaining class-related metadata.

String text = "Hello";

System.out.println(text.getClass()); 

Output

class java.lang.String

The getClass() method is called on the String object text to retrieve the Class object representing the String class.

  1. wait(), notify(), notifyAll(): These methods are used for thread synchronization and inter-thread communication. They are used in conjunction with the synchronized keyword to coordinate the execution of multiple threads.

How to Use the Object Class in Java Programming

To use the Object class in Java, you simply need to create an instance of a class. Since every class implicitly or explicitly extends the Object class, you can invoke its methods on any object. Here's an object class in Java example:

public class Car {
    private String brand;
    private int year;

    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    @Override
    public String toString() {
        return "Car(" +
               "brand='" + brand + '\'' +
               ", year=" + year +
               ')';
    }

    // Other methods and properties...

    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2022);
        System.out.println(myCar.toString());
    }
}

Output:

The output of the code will be Car{brand='Toyota', year=2022} (string representation of the Car object with brand "Toyota" and year 2022).

Object Class Methods: Description and Examples

The Object class in Java provides several methods available to all Java classes since every class implicitly extends the Object class. There are 11 methods of object class in Java. They include:

  1. equals(Object obj): Compares the current object with the specified object for equality.

  2. hashCode(): Returns the hash code value for the object.

  3. toString(): Returns a string representation of the object.

  4. getClass(): Returns the runtime class of the object.

  5. clone(): Creates and returns a copy of the object.

  6. finalize(): Called by the garbage collector before the object is reclaimed.

  7. notify(): Wakes up a single thread waiting on the object's monitor.

  8. notifyAll(): Wakes up all threads waiting on the object's monitor.

  9. wait(): Causes the current thread to wait until another thread notifies it.

  10. wait(long timeout): Causes the current thread to wait for a specified period of time.

  11. wait(long timeout, int nanos): Causes the current thread to wait for a specified period of time with nanoseconds.

These methods provide essential functionality for objects in Java, including comparison, object state representation, concurrency management, and more. While some of these methods can be used as-is, others can be overridden in subclasses to customize their behavior according to the specific needs of the class. Note that the object class methods in Java 8 are pretty much the same as those listed above.

Now, let's explore some commonly used methods of the Object class in more detail.

1. hashCode() Method:

The hashCode() method returns a unique integer value associated with an object. It is used in hash-based data structures to store and retrieve objects efficiently. Here's an example:

import java.util.Objects;

public class Book {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    public static void main(String[] args) {
        Book book1 = new Book("Java Programming", "John Doe");
        Book book2 = new Book("Python Basics", "Jane Smith");

        System.out.println(book1.hashCode());
        System.out.println(book2.hashCode());
    }

    @Override
    public int hashCode() {
        return Objects.hash(title, author);
    }
}

Output:

In this example, we override the hashCode() method to consider both the title and author attributes when computing the hash code.

2. toString() Method

The toString() method returns a string representation of an object. It is commonly used for printing meaningful information about an object.

3. equals(Object obj) Method

The equals() method compares two objects for equality. By default, it performs a reference comparison but can be overridden to provide custom equality checks. Here's an example:

public class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public static void main(String[] args) {
        Point point1 = new Point(2, 3);
        Point point2 = new Point(2, 3);
        Point point3 = new Point(4, 5);

        System.out.println(point1.equals(point2)); // true
        System.out.println(point1.equals(point3)); // false
    }

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

Output: 

In this example, we override the equals() method to compare the x and y coordinates of two point objects for equality.

Best Practices for Using Object Class Methods in Java Programming

Here are some best practices to keep in mind when using Object class methods in Java programming:

  • Override equals() and hashCode() together: When overriding the equals() method, it is recommended to override the hashCode() method as well. This ensures that equal objects have the same hash code, as required by hash-based data structures.

  • Provide meaningful toString() representations: Override the toString() method to provide a concise and informative representation of your objects. This can greatly aid in debugging and logging.

  • Use instanceof for type checking: When overriding the equals() method, use the instanceof operator to check the type of the incoming object. This helps avoid potential ClassCastException errors.

Overriding Object Class Methods

In Java, you can override methods of the Object class to provide customized behavior for your classes. Let's consider the examples we discussed earlier:

1. Overriding equals() method:

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null || getClass() != obj.getClass()) {
        return false;
    }
    Employee other = (Employee) obj;
    return Objects.equals(name, other.name) && age == other.age; // Corrected 'age other.age' to 'age == other.age'
}

In this example, we override the equals() method of the Employee class to compare the name and age attributes of two Employee objects.

2. Overriding hashCode() method:

@override
 Public int hashcode() {
       Return objects.hash(name, age);

In this example, we override the hashCode() method of the Employee class to consider both the name and age attributes when computing the hash code.

Object Class and Inheritance

The Object class plays a crucial role in inheritance in Java. By default, when a class does not explicitly extend another class, it automatically inherits from the Object class. This allows for polymorphism, where objects of different classes can be treated as objects of the Object class.

Best Practices for Using the Object Class in Inheritance Hierarchy:

  • Implement appropriate equals() and hashCode() methods in subclasses: When creating a subclass, override the equals() and hashCode() methods if the subclass introduces new attributes or changes the equality criteria.

  • Consider overriding toString() for enhanced readability: Override the toString() method in subclasses to provide a more descriptive representation of the subclass-specific attributes.

Benefits of Object Class in Java

The Object class in Java provides a solid foundation for object-oriented programming. Its benefits include:

  • Code Reusability: Inheriting the methods and properties of the Object class allows for code reuse across different classes.

  • Polymorphism: The Object class enables polymorphism, allowing objects of different classes to be treated as objects of the Object class.

  • Reflection and Introspection: The getClass() method of the Object class facilitates reflection and introspection, enabling dynamic retrieval of class information at runtime.

Conclusion

The Object class in Java serves as the cornerstone of Java programming. Understanding its characteristics, methods, and proper usage is essential for every Java developer. By leveraging the Object class effectively, you can enhance code reusability, achieve polymorphism, and implement various object-oriented programming concepts. So dive deep into the Object class, explore its methods, and unlock the full potential of Java programming. Happy coding!

FAQs

1. How does the Object class in Java serve as the foundation for all other classes?

The Object class acts as the universal superclass, and any class that does not explicitly extend another class inherits the Object class by default.

2. How can I compare objects for equality using the equals() method?

The equals() method compares two objects for equality by default, checking if the references of the two objects point to the same memory location. It can be overridden in derived classes to provide custom equality checks based on object attributes.

3. How can I obtain a string representation of an object using the toString() method?

The toString() method returns a string representation of an object. By default, it returns the class name followed by the object's hash code. It can be overridden in derived classes to provide a more descriptive representation.

4. How can I generate a unique hash code for an object using the hashCode() method?

The hashCode() method returns a unique integer value associated with an object. It is primarily used in hashing-based data structures like HashMap and HashSet. When overriding the equals() method, it is recommended to override the hashCode() method as well to maintain consistency.

5. How to create an object in Java?

There are five ways to create an object in Java.

  • Using ‘new’ Keyword

  • Using ‘clone(‘) method

  • Using ‘newInstance()’ method of the Class class

  • Using ‘newInstance()’ method of the Constructor class

  • Using ‘Deserialization’

Leave a Reply

Your email address will not be published. Required fields are marked *