July 7, 2008

Chapter: Reusing Classes

Create a class called Amphibian. From this, inherit a class called Frog. Put appropriate methods in the base class. In main(), create a Frog and upcast it to Amphibian and demonstrate that all the methods will work.


In Java:
package chapter.reusingClasses;

class Amphibian {

private void move() {
System.out.println("Moving");
}

private void swim() {
System.out.println("Swimming");
}

static void travel(Amphibian a) {
a.move();
a.swim();
}
}

class Frog extends Amphibian {

}

public class Exercise16 {

public static void main(String[] args) {

Frog kermit = new Frog();

Amphibian.travel(kermit);

}

}


In Python:
class Amphibian:
def move(self):
print "Moving"

def swim(self):
print "Swimming"

def travel(self):
self.move()
self.swim()

class Frog(Amphibian):
pass

frog = Frog()
frog.travel()

0 comments: