O
Ook
I have a class, Item. I have subclasses, CD, DVD, Book, etc (public
class Book extends Item). In the subclass Book, for example, I have a
method that returns the author of the book. I want to call this from a
class outside of the Item class, and I do it like this:
lcAuthor = item.author();
In Book I have:
public String author(){ return author; }
In Item I have the same thing. Because the method exists in Book, the
one in Item doesn't get called. This works fine. However, if I remove
the method from Item, I get a compilation error because there is no
item.author, even though there is a book.author.
I can fix this by calling item.author like this:
lcAuthor = ((Book) item).author();
This also works. My question - which should I do? Should I leave the
dummy call in my Item class that doesn't do anything? Is it better to
cast item to Book? Or is there a better way to handle this?
class Book extends Item). In the subclass Book, for example, I have a
method that returns the author of the book. I want to call this from a
class outside of the Item class, and I do it like this:
lcAuthor = item.author();
In Book I have:
public String author(){ return author; }
In Item I have the same thing. Because the method exists in Book, the
one in Item doesn't get called. This works fine. However, if I remove
the method from Item, I get a compilation error because there is no
item.author, even though there is a book.author.
I can fix this by calling item.author like this:
lcAuthor = ((Book) item).author();
This also works. My question - which should I do? Should I leave the
dummy call in my Item class that doesn't do anything? Is it better to
cast item to Book? Or is there a better way to handle this?