2012-07-12 76 views
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!爲什麼?

+0

你檢查什麼類型的變量? – berry120 2012-07-12 11:20:54

回答

8

如果你這樣做:

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

你會看到ofcourse正在打印"OK!",因爲FolderInfoItemInfo一個子類 - 所以FolderInfo也是ItemInfo對象。

繼承意味着從子類到超類存在「是」關係 - 請參閱Liskov substitution principle

0

InstanceOf是檢查IS A的關係。

if(ChildClass instanceOd ParentClass)總是返回你true。即使所有的類都實現接口A會通過的(AllClassess instanceOf A)

測試你的情況FolderInfoItemInfo

1

您可以通過鍵入檢查:

if (iteminfo instanceof FolderInfo) { 
// do what you want 
} 
else if (iteminfo instanceof ItemInfo) { 
// do what you want 
} 
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) { 
    }