A computer program is going to process animal objects. There are 4 kinds of animals (see above).
Click on the class definitions of each animal. What do you notice?
The information below is intended to support your understanding of the basics of Inheritance.
However, it is recommended that you complete intro task first which will get you coding quickly!
We can see that every class is very similar. In fact, the only difference is the name of the class and the name of the constructor method.
Each class has the same 2 properties.
This is because each class represents an animal and animals in this scenario are very similar.
They have the same properties/attributes and the same methods/actions.
This is because they are all animals!
If we can identify an IS-A relationship between classes, then we should consider using the OOP concept of inheritance.
A super class will define what every Animal is by defining the common properties and methods of all Animals.
Subclasses eg Bird, Bunny etc will need to create an IS-A relationship with the super class. In Java, the keyword extends is used to do this.
Any properties and methods that are already defined in the superclass can be removed from the subclass(es)!
You can see that the Bird class currently has no properties! Actually, they are defined in the superclass.
Also, there are no accessor/mutator methods!! These are defined in the superclass too!
There is still a constructor method because in another class we still need to be able to do this:
But how can we assign the name "Cecil" to the property name which is defined in the superclass?
We simply pass this to the super constructor when we construct a Bird;
As well as the keyword extends, java uses the keyword super when we need to refer to the superclass, and super() refers to the super constructor!
The video showed us:
When 2 or more classes display an IS-A relationship, we can use INHERITANCE.
This involves creating a superclass.
All subclasses can inherit properties and methods from this superclass.
Click the exercises button and see if you can complete the challenges.
object
property
method
create an object/instance of a class
instantiate an object
encapsulate
access
mutate
abstraction
idesyntax file class instantiate constructor type propertymethod