- Create a Class: Dog. Dog extends Pet. As a pet, dog or fish or bird, they all have common features, like eat, sleep, and say. We call this relationship as inheritance. On the other hand, different Pet has different behaviors or attributes to others. Dogs run, fish dive and don’t say. Therefore, we create a class Dog that will inherit some common behavior and attributes from the class Pet, rather than creating Dog or Fish with all commons.
Figure 1 Create Dog Class
- In Dog Class, we move the method run from Pet Class since we realized that not all Pets can run, for example, fish. The method run should not be a common behavior
Figure 2 Dog Class Code
- Create a class: DogMaster. We can clearly see that mydog Object in DogMaster can eat and sleep, which are common behavior defined in Pet. We did not define specific behavior of eat or sleep in Dog, but mydog can still use those methods, just because D
- og extends Pet (inheritance).
Figure 3 Create Class DogMaster
Figure 4 DogMaster Class
- Run DogMaster as an application, we can find the result in the console:
Figure 5 DogMaster Running Console
- “Good night!” is the result from mydog.sleep(), which is the method defined in Class Pet();
- “I’m so hungry…let me have a pizza!” is the result from mydog.eat(), which is the method defined in Class Pet();
- “OK!! OK!! arf-arf!arf-arf!” is the result from mydog.say(), which is the method defined in Class Pet();
- “I am going to run 40 KM” is the result from mydog.run(), which is the method defined in Class Dog(),the result from as we understand run is a specific method only owned by Dog, not common for all Pet.