Wednesday, November 17, 2021

Object Class in Java

Object class in Java is root class of all classes in Java. Each class in Java descend from Object class directly or indirectly. Object class is implicitly extended by a class if it is not extending any other class. In case, a class is extending any other class then also it extends Object class as a multi-level hierarchy inheritance.

As example if we have a class Employee

public class Employee {

}

It is same as

public class Employee extends Object {

}

Since it is implicitly extended by a class so you don’t need to write explicitly that your class is extending Object class.

Methods in Object class in Java

Every class you use or write inherits the instance methods of Object class. In case you need to use methods inherited from the Object class you may need to override them with code that is specific to your class.

Method Description
clone()Creates and returns a copy of this object.
boolean equals(Object obj)Indicates whether some other object is "equal to" this one.
protected void finalize()Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Class<?> getClass()Returns the runtime class of this Object.
int hashCode()Returns a hash code value for the object.
void notify()Wakes up a single thread that is waiting on this object's monitor.
void notifyAll()Wakes up all threads that are waiting on this object's monitor.
String toString()Returns a string representation of the object.
void wait()Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
void wait(long timeout)Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
void wait(long timeout, int nanos)Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

The clone() Method

If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method of the Object class to create a copy from an existing object. To create a clone, you write:

cloneableObject.clone();

The equals() and hashCode() Methods

The equals() method compares two objects for equality and returns true if they are equal.

The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal. If you override the equals() method, you must also override the hashCode() method as well.

The finalize() Method

The Object class in Java provides a callback method, finalize(), that may be invoked on an object when it becomes garbage. Though Object's implementation of finalize() does nothing and you have to override finalize() to do cleanup, such as freeing resources.

The getClass() Method

The getClass() method of the Object class returns a Class object, which has methods you can use to get information about the class, such as its name (getSimpleName()), its superclass (getSuperclass()), and the interfaces it implements (getInterfaces()).

Note that you cannot override getClass method.

Following example shows the use of getClass() method to display the class name of an object.

public class Car {
  public static void main(String[] args){
    Car car = new Car();
    car.printClassName(car);
  }
  void printClassName(Object obj) {
    System.out.println("The object's" + " class is " +
        obj.getClass().getSimpleName());
  }
}

Output

The object's class is Car

The toString() Method

The Object's toString() method returns a String representation of the object, which is very useful for debugging.

You should always consider overriding the toString() method in your classes. In your class You can use toString() along with System.out.println() to display a text representation of an object. In System.out.println() you can provide an object to get all the values and verify those values.

public class Employee {
 int empId;
 String name;
 String dept;
 Employee(int empId, String name, String dept){
  this.empId = empId;
  this.name = name;
  this.dept = dept;
 }
  
 public String toString(){
  return "EmpId = " + empId + " name= " + name + " dept = " + 
  dept;
 }
 public static void main(String args[]){  
  Employee emp1 = new Employee(1, "Ram", "IT");
  Employee emp2 = new Employee(2, "Krishna", "IT");
  System.out.println("Employee1- " + emp1);
  System.out.println("Employee2- " + emp2);
 }
}

Output

Employee1- EmpId = 1 name= Ram dept = IT
Employee2- EmpId = 2 name= Krishna dept = IT

If you don't override toString() method then on prining the object directly you won't get the text representation of the object just the object reference would be displayed. In the previous example you can comment the toString() method, in that case output will be as follows.

Employee1- org.netjs.examples1.Employee@659e0bfd
Employee2- org.netjs.examples1.Employee@2a139a55

wait(), notify() and noitfyAll() methods

wait() method causes the currently executing thread to wait.

notify() method wakes up a single thread waiting on this object’s monitor.

noitfyAll() method wakes up all threads that are waiting on this object's monitor.

Advantages of Object class in Java

  • Since Object class is the super class for all the classes so Object class can be used as a parameter or reference for any class object which helps in making your code more generic and following object oriented principles like polymorphism and dynamic method dispatch.
  • Though with introduction of Generics in Java 5, Object class has lost some of its sheen and now it is not that ubiquitous in code as it used to be. Before generics all collection were storing objects inherently as Object and we needed to typecast them (by downcasting from Object class reference to your class object) to the custom object while retrieving them.
  • Object class also provides some methods that are applicable to all classes and provides basic implementation too which can be overridden by the class wanting to use those methods.

Reference: https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html

That's all for this topic Object Class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Vs finally Vs finalize in Java
  2. instanceof Operator in Java With Examples
  3. String in Java Tutorial
  4. Type Erasure in Java Generics
  5. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block

You may also like-

  1. this Keyword in Java With Examples
  2. super Keyword in Java With Examples
  3. Nested class and Inner class in Java
  4. Transient in Java
  5. Java ThreadLocal Class With Examples
  6. Executor And ExecutorService in Java With Examples
  7. Fail-Fast Vs Fail-Safe Iterator in Java
  8. Multi-Catch Statement in Java Exception Handling

No comments:

Post a Comment