Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Object Class

The Object class is the root class of the Java class hierarchy. Every class in Java implicitly extends the Object class, which means that every Java object is an instance of the Object class or one of its subclasses. In this tutorial, we will cover the basics of the Java Object class, including some of the key methods provided by this class.

  • toString():

The toString() method returns a string representation of the object. By default, this method returns the object's class name, followed by an '@' sign and the object's hash code in hexadecimal. You can override the toString() method in your own classes to provide a more meaningful string representation.

Example:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

public class Main {
    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);
        System.out.println(person); // Output: Person{name='John Doe', age=30}
    }
}
  • equals():

The equals() method checks if two objects are equal. By default, this method compares the memory addresses of the objects, which is the same behavior as the '==' operator. You can override the equals() method in your own classes to provide a more meaningful equality comparison based on the object's properties.

Example:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John Doe", 30);
        Person person2 = new Person("John Doe", 30);

        System.out.println(person1.equals(person2)); // Output: true
    }
}
  • hashCode():

The hashCode() method returns a hash code for the object. This method should be overridden whenever you override the equals() method to maintain the general contract between hashCode() and equals(). Objects that are equal according to the equals() method should have the same hash code.

Example:

import java.util.Objects;

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        // ... (same as previous example)
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
  • clone():

The clone() method creates a new object that is a shallow copy of the original object. This method is protected and should be overridden in your own classes if you want to provide a way to clone objects. Note that the Cloneable interface should be implemented as well.

  1. Java Object class equals method:

    • The equals method is used to compare the content equality of two objects. It's often overridden in user-defined classes to provide meaningful comparisons.
    public class MyClass {
        @Override
        public boolean equals(Object obj) {
            // Implementation for content equality
        }
    }
    
  2. Java Object class hashCode method:

    • The hashCode method returns a hash code value for an object, which is used in hash-based collections like HashMap.
    public class MyClass {
        @Override
        public int hashCode() {
            // Implementation for generating hash code
        }
    }
    
  3. Using toString() in Java Object class:

    • The toString method returns a string representation of the object. It's often overridden to provide a meaningful representation.
    public class MyClass {
        @Override
        public String toString() {
            // Implementation for generating string representation
        }
    }
    
  4. Java clone method in Object class:

    • The clone method creates a shallow copy of the object. To support cloning, a class must implement the Cloneable interface.
    public class MyClass implements Cloneable {
        @Override
        public Object clone() throws CloneNotSupportedException {
            // Implementation for creating a copy
        }
    }
    
  5. Java Object class getClass method:

    • The getClass method returns the runtime class of an object, providing information about the class type.
    public class MyClass {
        public void printClass() {
            Class<?> clazz = this.getClass();
            System.out.println(clazz.getName());
        }
    }
    
  6. Java Object class and instanceof operator:

    • The instanceof operator checks if an object is an instance of a particular class or interface.
    public class MyClass {
        public void checkType(Object obj) {
            if (obj instanceof String) {
                // It's a String
            } else {
                // It's not a String
            }
        }
    }
    
  7. Java Object class and finalize method:

    • The finalize method is called by the garbage collector before reclaiming the object's memory. It's rarely used due to its unpredictable nature.
    public class MyClass {
        @Override
        protected void finalize() throws Throwable {
            // Cleanup operations before object is garbage-collected
        }
    }
    
  8. Overriding methods in the Java Object class:

    • Many methods in the Object class, such as equals, hashCode, and toString, are often overridden in user-defined classes to provide custom behavior.
    public class CustomClass {
        @Override
        public boolean equals(Object obj) {
            // Custom equals implementation
        }
    
        @Override
        public int hashCode() {
            // Custom hashCode implementation
        }
    
        @Override
        public String toString() {
            // Custom toString implementation
        }
    }
    
  9. Java Object class and polymorphism:

    • Polymorphism allows objects to be treated as instances of their superclass. The Object class serves as the ultimate superclass for all Java classes.
    Object obj = new MyClass();
    
  10. Java Object class and encapsulation:

    • Encapsulation involves hiding the internal details of an object. The Object class provides basic support for encapsulation through methods like equals, hashCode, and toString.
    public class MyClass {
        private int data;
    
        // Getter and setter methods
    }
    
  11. Java Object class and serialization:

    • Serialization is the process of converting an object into a byte stream. The Object class supports serialization through the Serializable interface.
    public class MyClass implements Serializable {
        // Class implementation
    }