Originally posted by Seany Iris:
What will be the output when the following code is run?
1. class ThisClass{
2. public static void main(String args[]){
3. Object o=(Object)new ThisClass();
4. Object s=new Object();
5. if(o.equals(s))
6. System.out.println("true");
7. }
8. }
The answer is No output. Why ? Because the method equals() be overridden.
The equals() method in Object and all Object extends it. So you can override this method in new SubClass.
String , Integer .... etc class all override this method, so you can see if their content is same the result is true. But more object do not rewrite this method, the result is all false, like StringBuffer or Untitled5 .
Exp:
public class Untitled5 {
public static void main( String[] args[]){
Object obj0 = new Object();
Object obj1 = new Object();
Object obj2=(Object) new Untitled5() ;
Untitled5 u5_0 = new Untitled5() ;
Untitled5 u5_1 = new Untitled5() ;
Integer i_0 = new Integer(3);
Integer i_1 = new Integer(3);
System.out.println("obj0 equals obj1 ? "+obj0.equals(obj1));
System.out.println("obj0 equals obj2 ? "+obj0.equals(obj2));
System.out.println("u5_0 equals u5_1 ? "+u5_0.equals(u5_1));
System.out.println("i_0 equals i_1 ? "+i_0.equals(i_1));
}
}
The result is :
obj0 equals obj1 ? false
obj0 equals obj2 ? false
u5_0 equals u5_1 ? false
i_0 equals i_1 ? true