Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 953
artem Avatar asked Jul 30 '26 19:07

artem


1 Answers

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.

like image 131
Jesper Avatar answered Aug 02 '26 08:08

Jesper