Inheritance is a fundamental part of object orientated programming. It allows you to inherit or use parts of other classes within a specific class. This is especially useful when you want to create two very similar classes that have very minor differences. Rather than copying the code from one class and placing it in another you can simply inherit it.
In our last tutorial we created a class called Dog.
Now imagine I wanted to create a class called Cat that was identical to Dog in almost every way. Right now with our current understanding of objects we would need to copy all of the code from our dog class. This is where we use inheritance!
Parent and Child Class
There is a bit of vocabulary we need to know before moving on.
Parent Class: This is the class that is inherited from (for our example it is the Dog class).
Child Class: This is the class that inherits from a parent class (in our case the Cat class).
Note: The parent class is also known as a super class and the child class is also known as a derived class.
So lets create our Cat class and see how to inherit everything from our Dog class.
And that's all there is to it. We simply use the word extends to tell our Cat class to use everything from our Dog class.
Note: We can extend more than one class.
Protected Access Modifier
Now time to talk about the protected keyword. When dealing with inheritance we need to modify the access modifiers of our parents class attributes to be protected. This is because a private access modifier will only allow for attributes to be modified within the parent class. However, we need to be able to change those attributes from within the child class as well. This is what protected allows for, changes within any child class as well as the parent class.
So we will change the dog class to look like the following:
Okay so this is all great, but what if we want to add an attribute to our Cat class called food. Well to do this we need to modify our Cat class slightly.
What we've done when we use the super keyword is call the constructor of our parent class (the Dog class).
Sometimes we want to change how a method works from inside our child class. In this case we may want to change the speak method so that it says something else. To do this all we need to do is redefine the speak method in our Cat class. Java will know to use the speak method inside of the Cat class instead of the inherited one from Dog.
Now when we call speak on a Cat object we will get a different output.
Now that we've added this food attribute we should also add a getter and setter for food.
Now our Cat class will have all of the getters and setters from our dog class as well as ones for its own food attribute.
Creating a Cat Object
Hopefully an example can help illustrate what I've discussed above.