黑马程序员技术交流社区

标题: 关于22行代码的问题 [打印本页]

作者: 唕    时间: 2014-8-7 23:48
标题: 关于22行代码的问题
本帖最后由 唕 于 2014-8-8 00:23 编辑
  1. <p>class Parent implements Comparable {
  2.         private int age = 0;
  3.         public Parent(int age){
  4.                 this.age = age;
  5.         }
  6.         public int compareTo(Object o) {
  7.                 // TODO Auto-generated method stub
  8.                 System.out.println("method of parent");
  9.                 Parent o1 = (Parent)o;
  10.                 return age>o1.age?1:age<o1.age?-1:0;
  11.         }
  12. }
  13. class Child extends Parent {

  14.         public Child(){
  15.                 super(3);
  16.         }
  17.         public int compareTo(Object o) {

  18.                         // TODO Auto-generated method stub
  19.                         System.out.println("method of child");
  20.                 //Child o1 = (Child)o;
  21.                         return 1;

  22.         }
  23. }

  24. public class Test8 {

  25.         /**
  26.          * @param args
  27.          */
  28.         public static void main(String[] args) {
  29.                 // TODO Auto-generated method stub
  30.                 TreeSet set = new TreeSet();
  31.                 set.add(new Parent(3));
  32.                 set.add(new Child());
  33.                 set.add(new Parent(4));
  34.                 System.out.println(set.size());
  35.         }

  36. }</p><p>第22行代码 应不应该存在 ,存在报错、  </p><p>求解释</p>
复制代码



作者: hjfeng1987    时间: 2014-8-8 18:11
Parent p=new Parent(3);
Child o1 = (Child)p;
当引用类型的真实身份是父类本身的类型时,强制类型转换就会产生错误

1、 第一次set.add(new Parent(3));
    执行Parent的compareTo,o的真实类型Parent对象
    Parent o1 = (Parent)o;运行通过

2、第二次 set.add(new Child());
    执行Child的compareTo,o的真实类型是第一次放进的Parent对象
    Child o1 = (Child)o; // Child o1 = (Child)o  o是Perentt  转换出错
作者: 唕    时间: 2014-8-8 20:39
hjfeng1987 发表于 2014-8-8 18:11
Parent p=new Parent(3);
Child o1 = (Child)p;
当引用类型的真实身份是父类本身的类型时,强制类型转换就 ...

好像是那么回事
作者: wisely    时间: 2014-8-8 21:06
set.add(new Child());
这句代码是关键。
底层调用Child的compareTo方法,跟前面一个parent比较,如果用代码表示就是下面这样。
new Child().compareTo(new Parent(3))
这就出问题了,按照Child中的方法,会将new Parent(3)转换成Child,但父类根本无法转换成子类对象。




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