3

我有两节课:

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!为什么?

4

4 回答 4

8

如果你这样做:

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

你当然会看到"OK!"被打印出来,因为FolderInfo是一个子类ItemInfo- 所以 aFolderInfo也是一个ItemInfo对象。

继承意味着从子类到超类存在“是”关系 - 参见Liskov 替换原则

于 2012-07-12T11:21:08.147 回答
1

您可以通过键入以下内容进行检查:

if (iteminfo instanceof FolderInfo) {
// do what you want
}
else if (iteminfo instanceof ItemInfo) {
// do what you want
}
于 2012-07-12T11:26:43.910 回答
0

InstanceOf是检查IS A关系。

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

在您的情况下, FolderInfoItemInfo

于 2012-07-12T11:24:32.447 回答
0

我建议您使用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) {
  }
于 2012-07-12T11:27:58.767 回答