July 7, 2008

Chapter: Polymorphism

Create an inheritance hierarchy of Rodent: Mouse, Gerbil, and Hamster. In the base class, provide methods that are common to all Rodents, and override these in the derived classes to perform different behaviors depending on the specific type of Rodent. Create an array of Rodent, fill it with different types of Rodents, and call your base class methods to see what happens.


In Java:
package chapter.polymorphism;

class Rodent {
public void play() {
System.out.println("Rodent playing");
}
public void eat() {
System.out.println("Rodent eating");
}
}

class Mouse extends Rodent {
public void play() {
System.out.println("Mouse playing");
}
public void eat() {
System.out.println("Mouse eating");
}
}

class Gerbil extends Rodent {
public void play() {
System.out.println("Gerbil playing");
}
public void eat() {
System.out.println("Gerbil eating");
}
}

class Hamster extends Rodent {
public void play() {
System.out.println("Hamster playing");
}
public void eat() {
System.out.println("Hamster eating");
}
}

public class Exercise9 {
public static void main(String[] args) {
Rodent[] rodents = { new Rodent(), new Mouse(), new Gerbil(),
new Hamster() };

for (Rodent rodent : rodents) {
rodent.play();
rodent.eat();
}
}
}


In Python:
class Rodent:
def play(self): print 'Rodent playing'
def eat(self): print 'Rodent eating'

class Mouse(Rodent):
def play(self): print 'Mouse playing'
def eat(self): print 'Mouse eating'

class Gerbil(Rodent):
def play(self): print 'Gerbil playing'
def eat(self): print 'Gerbil eating'

class Hamster(Rodent):
def play(self): print 'Hamster playing'
def eat(self): print 'Hamster eating'

rodents = (Rodent(), Mouse(), Gerbil(), Hamster())
for rodent in rodents:
rodent.play()
rodent.eat()

0 comments: