`
无量
  • 浏览: 1133972 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JDK-Date类源码学习

阅读更多
这里模仿JDK源码实现了一个自定义的Date类
package com.out.util;

import sun.util.calendar.BaseCalendar;

/**
 * Date类的实质就是,一个重要的属性:长整型,用来表示距离1970.1.1 0点,这个距离的毫秒数(1秒=1000毫秒)
 * 如:1970年1月1号1时0分0秒   就是:60*1000  如果是1969年12月31号13点 就是:-60*1000
 * 1.为什么要实现Serializable接口?
 * 2.为什么要实现Cloneable接口?自定义类默认继承Object类,已经有clone方法了,直接覆盖或者不需要实现,为什么还要实现Cloneable接口
 * clone对象更快,要覆盖因为,直接clone,如果对象中属性是引用,那么就是浅复制,覆盖以实现深度复制
 * 3.为什么要实现Comparable接口?
 * 来实现日期的比较功能
 * @author huangqun08312
 */
public class Date implements java.io.Serializable, Cloneable,Comparable<Date>{
	
	/**
	 * 这个serialVersionUID什么作用,为什么是这样的数?
	 */
	private static final long serialVersionUID = 6660056718619883291L;
	
	/**
	 * transient关键字什么作用?
	 * transient关键字只能修饰变量,被transient关键字修饰的变量不能被序列化
	 * 一个静态变量不管是否被transient修饰都不能被序列化
	 */
	private transient long fastTime;
	
	private transient BaseCalendar.Date cdate;
	
	public Date() {
		this.fastTime = System.currentTimeMillis();
	}
	
	public Date(long date) {
		this.fastTime = date;
	}
	
	public long getTime() {
		return this.fastTime;
	}
	
	public void setTime(long time) {
		this.fastTime = time;
	}
	
	public boolean before(Date when) {
		return getMillisOf(this) < getMillisOf(when);
	}
	
	public boolean after(Date when) {
		return getMillisOf(this) > getMillisOf(when);
	}
	
	public boolean equals(Object obj) {
		return obj instanceof Date && getTime() == ((Date)obj).getTime();
	}
	
	/**
	 * final可以修饰方法么?
	 * final修饰的方法,不可以被子类覆盖,子类不可以复写
	 * final修饰的类,不可以被继承,也就是final修饰的类是叶子类
	 * @param date
	 * @return
	 */
	static final long getMillisOf(Date date) {
		return date.fastTime;
	}
	
	public int compareTo(Date other) {
		long thisTime = getMillisOf(this);
		long otherTime = getMillisOf(other);
		return thisTime > otherTime ? 1 : (thisTime == otherTime?0:-1) ;
	}
		
	public int hashCode() {
		long ht = this.getTime();
        return (int) ht ^ (int) (ht >> 32);
	}
	
	/**
	 * 这个克隆方法,为什么还要再判断下cdate这个是否为null,再克隆一次?
	 * 增加效率,如果为null,没必要在复制了
	 * Date这个克隆不可以直接把其属性和方法同时克隆么?
	 * 如果是基本类型,直接会复制一份,如果属性是引用类型,那么如果不实现clone方法,那样的复制是浅复制
	 */
	public Object clone() {
		Date d = null;
		try {
			d = (Date) super.clone();
			if (cdate != null) {
				d.cdate = (sun.util.calendar.BaseCalendar.Date) cdate.clone();
			}
		} catch (CloneNotSupportedException e) { }   //从来不会被执行到
		
		return d;
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics