Inheritance:Pet and Dog

  • 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.

createdogclass

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

dogclass

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).

dogmasterclass

Figure 3 Create Class DogMaster

dogmastercode

Figure 4 DogMaster Class

  • Run DogMaster as an application, we can find the result in the console:

dogmasterconsole

Figure 5 DogMaster Running Console

 

  1. Good night! is the result from mydog.sleep(), which is the method defined in Class Pet();
  2. I’m so hungry…let me have a pizza!” is the result from mydog.eat(), which is the method defined in Class Pet();
  3. OK!! OK!! arf-arf!arf-arf!” is the result from mydog.say(), which is the method defined in Class Pet();
  4. 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.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s