Jupyter at Bryn Mawr College |
|||
Public notebooks: /services/public/dblank / CS206 Data Structures / 2016-Spring / Notebooks |
In OOP, one can also create a class that is based on another class.
In this example, we make a base class Animal
to serve as the superclass of a subclass Dog
.
We say that a Dog is-a Animal.
For has-a relationships, we make those properties of the class (like has-a name).
class Animal {
public void speak() {
printf("I am an animal\n");
}
}
Animal animal = new Animal();
animal.speak();
class Dog extends Animal {
public void speak() {
printf("woof!\n");
}
}
Dog dog = new Dog();
dog.speak();
Animal whatisthis = dog;
whatisthis.speak();
The Dog object gets the message "speak" and it has a method for that.
This is called Polymorphism.
See Page 19 of your textbook for more details.