Jupyter at Bryn Mawr College |
|||
Public notebooks: /services/public/dblank / CS206 Data Structures / 2017-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");
}
public String getName() {
return "Animal";
}
}
Animal animal = new Animal();
animal.speak();
"I am an " + animal.getName();
class Dog extends Animal {
public void speak() {
printf("woof!\n");
}
}
class Cat extends Animal {
public void speak() {
printf("meow!\n");
}
void poopInBox() {
printf("wheeew");
}
}
Cat cat = new Cat();
cat.speak();
cat.getName();
dog.getName()
Dog dog = new Dog();
dog.speak();
Animal whatisthis = cat;
whatisthis.speak();
cat.poopInBox();
whatisthis.poopInBox();
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.