Object有8个常用方法。因为Object是所有类的基类,所以所有类都有这8个方法。
1)getClass()
getClass().getSimpleName()或者MainActivity.class.getSimpleName()可方便获得类名。
如android中打Log用的tag,private static final String TAG = getClass().getSimpleName()
2)toString()
查看类的信息,默认getClass().getName() + "@" + Integer.toHexString(hashCode())。可以覆写toString来打印想要的信息。
3)equals(Object)
比较两个对象是否相等。默认用“==”比较,只有相同对象才返回true。
4)hashCode()
一般两个不同对象哈希值也不同,HashSet和HashMap会用到此方法。
5)notify()及wait()
wait()方法引起当前线程等待,直到另一个线程调用notify()方法。
6)clone及finalize
clone(): create and return a copy of the object
finalize(): dispose of system resources or perform other cleanup
public class ObjectTest {
public static void main(String[] args) {
Student s = new Student("Victor", new Course(2104, "English"));
try {
//standard output stream. open and ready to accept output data
//PrintStream
System.out.println(s.clone());
//不同对象
System.out.println("s:"+s.hashCode()+";clone:"+s.clone().hashCode());
//field相同对象
System.out.println(s.getCourse().hashCode()+"|"+((Student) s.clone()).getCourse().hashCode());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
class Student extends Object implements Cloneable{
private String name;
private Course course;
public Student(String name,Course course){
this.name = name;
this.course = course;
}
public String getName() {
return name;
}
public Course getCourse() {
return course;
}
@Override
public Object clone() throws CloneNotSupportedException {
//protected
return super.clone();
}
@Override
protected void finalize() throws Throwable {
System.out.println(getClass().getSimpleName()+"-finalize");
//protected
super.finalize();
}
@Override
public String toString() {
//return a string representation of the object
return ";姓名:"+name+";课程:"+course;
}
}
class Course{
private int courseId;
private String courseName;
public Course(int courseId,String courseName){
this.courseId = courseId;
this.courseName = courseName;
}
public int getCourseId() {
return courseId;
}
public String getCourseName() {
return courseName;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
protected void finalize() throws Throwable {
//called by GC
System.out.println(getClass().getSimpleName()+"-finalize");
super.finalize();
}
@Override
public String toString() {
return ";课程编号:"+courseId+";课程名称:"+courseName;
}
}