artem
artem

Reputation: 16798

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?

Upvotes: 3

Views: 112

Answers (4)

Ramesh PVK
Ramesh PVK

Reputation: 15456

I would suggest you to use Enumeration defining all the types .

Here is how the above code will look like:

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

Which will allow you write better and neat code like this :

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

And wherever you want to check the type you can check like this:

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

Upvotes: 0

robi terebesi
robi terebesi

Reputation: 65

You can check by typing:

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

Upvotes: 1

amicngh
amicngh

Reputation: 7899

InstanceOf is a check for IS A relationship.

if(ChildClass instanceOd ParentClass) always returns you true. even all classes implement interface A will pass the test of (AllClassess instanceOf A)

In your case FolderInfo is a ItemInfo.

Upvotes: 0

Jesper
Jesper

Reputation: 206996

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.

Upvotes: 8

Related Questions