Forum Stats

  • 3,760,200 Users
  • 2,251,663 Discussions
  • 7,871,021 Comments

Discussions

Removing need for cast with generic possible?

843793
843793 Member Posts: 41,732 Green Ribbon
edited Apr 9, 2010 12:15AM in Generics
Hi,

I've had success with generics in some areas, but not this and wondered if and how you can remove the need to cast in the following example:
public abstract class Record {
	private String description = "Some Description";
	public String getDescription() {
		return description;
	}
}

public abstract class RecordDiskFile extends Record { 
	private String imagePath = "Some Image Path";	
	public String getImagePath() {
		return imagePath;
	}
}

public class Item extends RecordDiskFile {
}

Record item = new Item();
item.getDescription();    ----> works
item.getImagePath();     -----> fails and needs ((RecordDiskFile) item).getImagePath();
Thanks, Len

Comments

  • EJP
    EJP Member Posts: 32,920 Gold Crown
    The solution has nothing to do with Generics:
    public abstract class Record {
    private String description = "Some Description";
    public String getDescription() {
    return description;
    }
    public abstract String getImagePath();
    }
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    edited Apr 8, 2010 5:01PM
    getImagePath() shouldn't be visible in the base Record class, it belongs in the sub-class RecordDiskFile.

    Edited by: bocockli on Apr 8, 2010 2:00 PM
  • DrClap
    DrClap Member Posts: 25,479
    bocockli wrote:
    getImagePath() shouldn't be visible in the base Record class
    So Record isn't going to have a visible getImagePath() member? Then assigning the Item object to a Record variable is a programming error, if you want to use that member. You can't wave Generics at the problem and change that.
  • EJP
    EJP Member Posts: 32,920 Gold Crown
    getImagePath() shouldn't be visible in the base Record class, it belongs in the sub-class RecordDiskFile.
    Then you have to cast. No way round it.
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    Yeah, you're right - sometimes it's the wood from the trees; solved it within the factory that creates the record in the first place; generics work well there.
    Record item = recordFactory.create(Item.class);
    RecordDiskFileFactory.getImage(item);
    Thanks
This discussion has been closed.