Object Class
It is the parent class of all classes
in Java.
Method |
Description |
public
final Class getClass() |
returns
the Class class object of this object. The Class class can further be used to
get the metadata of this class. |
public
int hashCode() |
returns
the hashcode number for this object. |
public
boolean equals(Object obj) |
compares
the given object to this object. |
protected
Object clone() throws CloneNotSupportedException |
creates
and returns the exact copy (clone) of this object. |
public
String toString() |
returns
the string representation of this object. |
public
final void notify() |
wakes
up a single thread, waiting on this object's monitor. |
public
final void notifyAll() |
wakes
up all the threads, waiting on this object's monitor. |
public
final void wait(long timeout)throws InterruptedException |
causing
the current thread to wait for the specified milliseconds until another
thread notifies (invokes notify() or notifyAll() method). |
public
final void wait(long timeout, int nanos)throws InterruptedException |
causes
the current thread to wait for the specified milliseconds and nanoseconds until another thread notifies (invokes notify() or notifyAll() method). |
public
final void wait()throws InterruptedException |
causing
the current thread to wait until another thread notifies (invokes notify()
or notifyAll() method). |
protected
void finalize()throws Throwable |
is
invoked by the garbage collector before the object is being garbage collected. |
Example 01:
package com.java.ObjectClass;
public class ObjectClassExample {
private String name;
private int age;
public ObjectClassExample(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "ObjectClassExample{name='" + name + "', age=" + age + "}";
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true; // Check if the same reference
}
if (obj == null || getClass() != obj.getClass()) {
return false; // Check if types are different
}
ObjectClassExample other = (ObjectClassExample) obj;
return age == other.age && (name != null ? name.equals(other.name) : other.name == null);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
public static void main(String[] args) {
ObjectClassExample obj1 = new ObjectClassExample("Alice", 30);
ObjectClassExample obj2 = new ObjectClassExample("Alice", 30);
ObjectClassExample obj3 = new ObjectClassExample("Bob", 25);
// Using toString()
System.out.println("obj1: " + obj1.toString());
System.out.println("obj2: " + obj2);
// Using equals()
System.out.println("obj1 equals obj2: " + obj1.equals(obj2)); // true
System.out.println("obj1 equals obj3: " + obj1.equals(obj3)); // false
// Using hashCode()
System.out.println("obj1 hashCode: " + obj1.hashCode());
System.out.println("obj2 hashCode: " + obj2.hashCode());
System.out.println("obj3 hashCode: " + obj3.hashCode());
}
}
0 Comments