黑马程序员技术交流社区

标题: equals()方法中使用getClass()和instanceof方法的区别? [打印本页]

作者: 刘丰伟    时间: 2012-12-27 20:06
标题: equals()方法中使用getClass()和instanceof方法的区别?
还有就是什么时候使用啊,不懂!
作者: zjqlovelyy    时间: 2012-12-29 10:53
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
这是文档里面equals方法的说明,也就是说如果引用同一个对象的时候为true,否则为false。

下面这个是getClass的文档里面说明。
Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.
  1. class Demo
  2. {
  3.         void Show(){System.out.println(1);}
  4. }

  5. class Ins extends Demo
  6. {
  7.         void Method(){System.out.println(2);}
  8. }

  9. class Demo2
  10. {
  11.         public static void main(String []args)
  12.         {
  13.                 Ins ins = new Ins();
  14.                 Demo demo = new Demo();
  15.                 Object obj = new Object();
  16.                 Demo demo2 = new Demo();
  17.                 Demo demo3 = demo2;
  18.                 System.out.println(demo instanceof Ins);
  19.                 System.out.println(demo.equals(ins));
  20.                 System.out.println(demo instanceof Object);
  21.                 System.out.println(demo.equals(obj));
  22.                 System.out.println(demo.getClass()==obj.getClass());
  23.                 System.out.println(demo2.getClass()==demo.getClass());
  24.                 //System.out.println(demo2.==demo3);
  25.                
  26.         }
  27. }
复制代码

未命名.jpg (10.38 KB, 下载次数: 25)

未命名.jpg





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2