Object方法

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;
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值