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

JSP page directives

A jsp page directive looks like this: <%@ directive attribute="value" %> I am not gonna explain each and every page directives here . I would like to discuss about two page directives  which is import and include. First of all consider the import directive . The following simple program illustrate the use of import page directive: The output would be something looks like this: <%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%>  <%@ page import="java.util.Date" %>   //page directive <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Jsp Basics</title> </head> <body> <%=new Date() %> </body> </html> Tue Nov 12 17:42:34 I...

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...