Re: Polymorphism - please help me understand



Mike B <mxbNoSpam@xxxxxxx> wrote:
> How can this be true? In the Book and Software objects are data fields
> (variables) that are not in the Product object. Surely it cannot preserve
> fields it has no knowledge about?

The ProductDB class will do what its code tells it to do. If that code
reads and stores individual fields, then it will only store those fields
that it's programmed to read and store. For that reason, this
ProductDB.addRecord is probably a bad example. It would be possible to
make it work with polymorphism, but it would require writing knowledge
about the database into the Book and Software classes, which is
generally considered a bad idea.

> As an example, if I have a toString method
> in the Product class, I must still write a toString method in the
> Book/Software classes to return printable representations of the variables
> in those classes?

Yes, you absolutely do need to do that. Polymorphism says that if I have
a function like this:

public void printToLog(Product p)
{
logPrinter.println(p.toString());
}

Then I can do either:

printToLog(myBook);
printToLog(mySoftware);

and the toString() that's called from printToLog WILL be the toString()
that was defined in Book or Software, not the one defined in Product.
It's not magic; you still have to write the code... but when you write
the code for Book, for example, it can be called by someone who doesn't
necessarily know that they are working with a Book.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
.