【问题标题】:Classes inheritance类继承
【发布时间】:2012-07-12 03:14:36
【问题描述】:

我有两个班级:

class ItemInfo {

   public View createItemView() {
       View v;
       // ...
       v.setTag(this); 
       return v;
   }
}

class FolderInfo extends ItemInfo {

    @Override
    public View createItemView() {
        View v;
        // ...
        v.setTag(this);
        return v;
    }
}

然后我用它:

FolderInfo folderInfo;
// Create it here
ItemInfo itemInfo = folderInfo;
View v = itemInfo.createItemView();
Object objectTag = v.getTag();

然后我通过instanceof检查objectTag的类型,它是ItemInfo!为什么?

【问题讨论】:

  • 你检查的是什么变量的类型?

标签: java android oop inheritance instanceof


【解决方案1】:

如果你这样做:

if (itemInfo instanceof ItemInfo) {
    System.out.println("OK!");
}

您当然会看到"OK!" 被打印出来,因为FolderInfo 是ItemInfo 的子类——所以FolderInfo 也是ItemInfo 对象。

继承意味着从子类到超类存在“是”关系 - 请参阅Liskov substitution principle。

【讨论】:

    【解决方案2】:

    InstanceOf 是对IS A 关系的检查。

    if(ChildClass instanceOd ParentClass) 总是返回你true。甚至所有实现接口A的类都会通过(AllClassess instanceOf A)的测试

    在您的情况下,FolderInfo 是 ItemInfo。

    【讨论】:

      【解决方案3】:

      您可以输入以下内容进行检查:

      if (iteminfo instanceof FolderInfo) {
      // do what you want
      }
      else if (iteminfo instanceof ItemInfo) {
      // do what you want
      }
      

      【讨论】:

        【解决方案4】:

        我建议您使用Enumeration 定义所有类型。

        上面的代码如下所示:

        class View {
            public ItemInfo getTag() {
               return tag;
            }
        }
        
        enum ItemType {
            FolderType,
            FileType
        };
        
        
        class ItemInfo {
          private abstract ItemType getType();
        
         public View createItemView() {
           View v;
           // ...
           v.setTag(this); 
           return v;
          }
        }
        
        class FolderInfo extends ItemInfo {
        
        private  ItemType getType() {
          return ItemType.FolderType;
        }
        @Override
        public View createItemView() {
            View v;
            // ...
            v.setTag(this);
            return v;
          }
        }
        

        这会让你写出更好更整洁的代码:

        switch(itemType) {
              case ItemType.FolderType:
                  //handle folder type
                  break;
              case ItemType.FileType:
                  //handle folder type
                  break;
        }
        

        无论你想检查类型,你都可以像这样检查:

          if( itemInfo.getType() == ItemType.FolderType) {
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-23
          • 2015-03-14
          • 2010-11-08
          • 1970-01-01
          • 2023-03-27
          • 1970-01-01
          相关资源
          最近更新 更多