Skip to main content

Exploring the Java Object Class: A Comprehensive Guide to Its Methods with Examples

Java's Object Class and Its Methods

In Java, all classes inherit from the Object class, which provides several useful methods that are available to all classes. Understanding these methods is essential for writing effective and efficient Java code. In this article, we'll take a closer look at the Object class and its methods.


The Object Class

The Object class is a fundamental part of the Java language and is the superclass of all other classes. It provides several methods that are available to all classes. Here are some of the most commonly used methods:

equals()

The equals() method is used to compare two objects for equality. By default, it checks whether two objects are the same instance, but you can override it to define custom equality rules. Here's an 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 (obj == this) {
            return true;
        }

        if (!(obj instanceof Person)) {
            return false;
        }

        Person other = (Person) obj;

        return name.equals(other.name) && age == other.age;
    }
}

Person person1 = new Person("John", 30);
Person person2 = new Person("John", 30);
Person person3 = new Person("Jane", 25);

System.out.println(person1.equals(person2)); // Output: true
System.out.println(person1.equals(person3)); // Output: false

toString()

The toString() method returns a string representation of the object. By default, it returns the class name and memory address of the object, but you can override it to provide a custom string representation. Here's an 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 + "]";
    }
}

Person person = new Person("John", 30);
System.out.println(person.toString()); // Output: Person [name=John, age=30]

hashCode()

The hashCode() method returns a hash code value for the object. It's used for hashing-based data structures such as HashMap and HashSet. By default, it returns a hash code based on the memory address of the object, but you can override it to provide a custom implementation. Here's an example:

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

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

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

Person person = new Person("John", 30);
System.out.println(person.hashCode()); // Output: 123456

getClass()

The getClass() method returns the Class object associated with the object at runtime. It's useful for obtaining metadata about the class. Here's an example:

Person person = new Person("John", 30);
System.out.println(person.getClass().getName()); // Output: Person

wait(), notify(), and notifyAll()

The wait(), notify(), and notifyAll() methods are used for inter-thread communication and synchronization. They allow threads to communicate and coordinate with each other. Here's an example:

public class Message {
    private String content;
    private boolean available = false;

    public synchronized String receive() throws InterruptedException {
        while (!available) {
            wait();
        }

        available = false;
        notifyAll();
        return content;
    }

    public synchronized void send(String message) throws InterruptedException {
        while (available) {
            wait();
        }

        content = message;
        available = true;
        notifyAll();
    }
}

Message message = new Message();

Thread senderThread = new Thread(() -> {
    try {
        message.send("Hello!");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});

Thread receiverThread = new Thread(() -> {
    try {
        String receivedMessage = message.receive();
        System.out.println("Received: " + receivedMessage);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});

senderThread.start();
receiverThread.start();

The Object class is a fundamental part of Java and provides important methods that are inherited by all classes. Understanding these methods and their usage can greatly enhance your Java programming skills. Make sure to explore further and experiment with these methods to deepen your understanding.

Comments

Popular posts from this blog

a simple example for jdbc PreparedStatement

a simple example for PreparedStatement package basics.in.java.blogspot.in; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { private static final String USERNAME="root"; private static final String PASSWORD=""; private static final String CONN_STRING="jdbc:mysql://localhost/basicsinjavablogspot"; public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn=null; Statement stmt=null; ResultSet rs=null; try { conn= DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); System.out.println("database connection successful"); //stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql="select * fr...

Server-Side Pagination with React-Table and Spring Boot JPA with H2 Database

Pagination is a common technique used to split large amounts of data into smaller, more manageable chunks. With server-side pagination, data is retrieved from the server in smaller batches, reducing the amount of data transferred over the network and improving application performance. React-Table provides a wide range of built-in features such as sorting, filtering, pagination, row selection, and column resizing. These features can be easily configured and customized to fit specific requirements. For example, you can customize the sorting behavior to handle multiple sorting criteria, or you can add custom filters to the table to handle complex data filtering scenarios. Additionally, React-Table provides a flexible API that allows developers to extend its functionality with custom hooks, plugins, and components. This means that you can easily add custom functionality to the table, such as exporting data to CSV or integrating with external data sources. In terms of styl...