Home > Java > javaTutorial > body text

Detailed introduction to the Object class in Java

高洛峰
Release: 2017-01-17 16:43:24
Original
1440 people have browsed it

Theoretically, the Object class is the parent class of all classes, that is, it directly or indirectly inherits the java.lang.Object class. Since all classes inherit from the Object class, the extends Object keyword is omitted.
There are mainly the following methods in this class: toString(), getClass(), equals(), clone(), finalize(), among which toString(), getClass(), equals are the most important methods.

Note:

The getClass(), notify(), notifyAll(), wait() and other methods in the Object class are defined as final types and therefore cannot be overridden.

getClass() method;
cannot be overridden. If it is called, it is generally used in conjunction with getName(), such as getClass().getName();
toString() method;
Overridable; if a specific output mode is provided for a specific object in actual use, the overridden toString() method is automatically called when this type is converted to a string or string concatenation.

public ObjectInstance{
public String toString(){
 return "在"+getClass().getName()+"重写toString()方法"
}
public static void main(String arg[]){
  System.out.println(new ObjectInstance());
}
}
Copy after login


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));
  }
}
Copy after login

Output result:

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


From this example It can be seen that when using the equals() method in a custom class for comparison, false will be returned because the default implementation of the equals method is the "==" operator, which compares the reference addresses of two objects instead of comparing objects. Content. So if you want to truly compare the contents of two objects, you need to override the equals() method in the custom class.

For more detailed introduction to the Object class in Java and related articles, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template