首页 > 代码库 > java中Object.equals()简单用法

java中Object.equals()简单用法

/*equals()方法默认的比较两个对象的引用!*/class Child {    int num;	public Child(int x){	    num = x;	}		//人文的抛出运行时异常的好处是:可以自定义错误信息!		/*public boolean equals(Object o) throws ClassCastException{	     if(!(o instanceof Child)) throw new ClassCastException("中文提示:类型错误");	     Child ch = (Child) o;		 return num == ch.num ;	}*/		/*	    Exception in thread "main" java.lang.ClassCastException: 中文提示:类型错误        at Child.equals(PC.java:8)        at PC.main(PC.java:17)	*/		public boolean equals(Object o){	     Child ch = (Child) o;		 return num == ch.num ;	}		/*	    Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot	    be cast to Child        at Child.equals(PC.java:14)        at PC.main(PC.java:22)	*/}public class PC{     public static void main(String[] args){	    Child p1 = new Child(11);		if(p1.equals(new Integer(11)))		   System.out.println("true");		   		System.out.println("这句话是否执行?");// 如果异常得到了处理, 那么这句话就会执行,否则就不会被执行!	 }}