-
Polymorphism discussion
I just started going for my bachelors degree in computer science(which means i have to rehash some basic concepts).:rolleyes: and my teacher wanted us to show some coding examples of polymorphism. Here is my attempt. Would anyone like to show
any of their examples and or tips. :)
Code:
import java.util.*;
public class X {
public static void main(String[] args){
Vector v = new Vector();
v.addElement(new Superhero());
v.addElement(new Sidekick());
Iterator i = v.iterator();
while(i.hasNext()){
Superhero s = (Superhero)i.next();
s.printStatus();
}
}
}
class Superhero {
public void printStatus(){
System.out.println("I am the super hero!");
}
}
class Sidekick extends Superhero{
public void printStatus(){
System.out.println("I am a side kick!");
}
}
-
Dont forget that overloading is a form of polymorphism.
-
I sort of disagree with your example. A sidekick should not be an extension of a super hero, you may need to add a class called person.
Person
Super Hero Side Kick Evil Villian (Bill who?)
Do you agree disagree?
-
The greatest thing I think poly gives a programmer is the ability to adapt to things.
The oldie but goodie shape example:
Say I have a shape class that has a draw method.
I then go on to make two new subclasses Circle and Rectangle, and give them their own draw method. Later I decide I need to support Triangles, so I create a new subclass called Triangle and with its own draw method. I didnt have to change any pre existing code to add support of triangles. Now that is a beautiful thing.
-
Yes i totaly agree with you in the respect that a sidekick should not be an extension of a superhero. As you have pointed out a superhero should probably be an extension of a person.