The Object class in Java is described in detail

  • 2020-04-01 03:57:31
  • OfStack

Theoretically, the Object class is the parent of all classes, that is, directly or indirectly inherits the java.lang.object class. Since all classes inherit from the Object class, the extends Object keyword is omitted.
The main methods in this class are toString(),getClass(),equals(),clone(),finalize(), where toString(),getClass(),equals are the most important.

Note:

Methods such as getClass(),notify(),notifyAll(),wait() in the Object class are defined as final and therefore cannot be overridden.

GetClass () method;
It cannot be overridden, but is typically used in conjunction with getName(), such as getClass().getname ();  
The toString () method;
Can be rewritten; If in practice a particular output pattern is provided for a particular object, the overridden toString() method is automatically called when the type is converted to a string or string concatenation.    


public ObjectInstance{ 
public String toString(){ 
 return " in "+getClass().getName()+" rewrite toString() methods " 
} 
public static void main(String arg[]){ 
  System.out.println(new ObjectInstance()); 
} 
} 

The equals () method;


class V { 
} 
public class OverWriteEquals{ 
  public static void main(String args[]){ 
    String s1="123"; 
    String s2="123"; 
    System.out.println(s1.equals(s2)); 
    V v1= new V(); 
    V v2= new V(); 
    System.out.println(v1.equals(v2)); 
  } 
} 

Output results:


run: 
true 
false 
BUILD SUCCESSFUL (total time: 0 seconds) 

As you can see from this example, when using the equals() method for comparison in a custom class, false is returned because the default implementation of the equals method is the "==" operator, which compares the reference addresses of two objects rather than the contents of the objects. So to really compare the contents of two objects, you need to override the equals() method in your custom class.


Related articles: