We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Polymorphism and Arrays of Objects
Page Index Toggle Pages: 1
Polymorphism and Arrays of Objects (Read 691 times)
Polymorphism and Arrays of Objects
Mar 25th, 2010, 11:40am
 
I've got a class called "channel". I've written two subclasses for it, both of which implement the "poll" method, however "channel" itself does not. When I run this, I get an error indicating poll() does not exist.

Code:


for (int j = 0; j < channels.size(); j++) {
Channel the_channel = (Channel) channels.get(j);
output.print(str(the_channel.poll()));
}


If I cast the_channel to one of the subclass types it will work (so long as the array contains only those types), and I suppose I could add an if statement to check what it's an instance of, but this seems to defeat the point of polymorphism. What am I missing?
Re: Polymorphism and Arrays of Objects
Reply #1 - Mar 25th, 2010, 11:58am
 
Your class seems to be called Channel, not channel.
And you are right, checking the type of a sub-class is, sometime, necessary, but not in OOP spirit.

The solution is to add a poll() method to Channel.
Two cases:
- If you never create Channel objects, just declare it abstract, and add an abstract poll() method (no body) to it.
- Otherwise, add a poll() method returning an empty string, for example.
Re: Polymorphism and Arrays of Objects
Reply #2 - Mar 25th, 2010, 12:19pm
 
You could also make Channel an interface, and then implement it with each of the subclasses.
Page Index Toggle Pages: 1