Computer Science Canada Concept check |
Author: | Tubs [ Wed Jan 03, 2007 6:37 pm ] | ||
Post subject: | Concept check | ||
I was fiddling around with java concepts and ran into a snag.
How would I use the main method to handle any type of pet? Assuming I had 10 different kinds of animals, would I have to do an if statement for each animal's speak command? |
Author: | HellblazerX [ Wed Jan 03, 2007 8:21 pm ] |
Post subject: | |
I believe you would need abstract classes for this. In your case, your class Pet would be an abstract class rather than a normal one. Rizzix wrote a nice little tutorial on abstract classes. |
Author: | Tubs [ Thu Jan 04, 2007 6:48 pm ] |
Post subject: | |
I can't create an instance of the type Pet if its an abstract class. |
Author: | wtd [ Thu Jan 04, 2007 8:29 pm ] | ||
Post subject: | |||
A fundamental conceptual mistake is occurring here.
Strings in Java are objects. This means that == does not check for structural equality, but rather referential equality. This will only be true if the two objects are the same. Two Strings can be structurally identical without being referentially identical. |
Author: | Tubs [ Thu Jan 04, 2007 11:02 pm ] |
Post subject: | |
I haven't looked at runtime logic errors yet, I'm more concerned about the abstract classes. Thanks for the tip though. |
Author: | HellblazerX [ Fri Jan 05, 2007 3:17 pm ] |
Post subject: | |
Tubs wrote: I can't create an instance of the type Pet if its an abstract class.
I suppose you could create a separate subclass for Generic Pets, but other than that, I don't think there's any other of doing it with abstract classes. |