Search code examples
javaandroidoopinheritanceinstanceof

Classes inheritance


I have two classes:

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;
    }
}

Then I use it:

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

Then I check type of objectTag by instanceof, and it's ItemInfo! Why?


Solution

  • If you do this:

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

    You'll ofcourse see "OK!" being printed, because FolderInfo is a subclass of ItemInfo - so a FolderInfo is also an ItemInfo object.

    Inheritance means that there is an "is a" relationship from the subclass to the superclass - see Liskov substitution principle.