Inheritance is when one class inherits all the fields (variables) and methods from another class. Think of it as mashing together two different classes into one. The class inherited from is referred to as the superclass (or parent class) and the class that inherits the subclass (or child class). When you inherit from another class you can choose to override the methods or use the parent class’ methods. Constructors are not inherited, but we can refer to the parents constructor if we need to.
We have learned many features that allow us to simplify our code: methods, classes, etc. Inheritance allows us to further reuse our code by being able to inherit another class and add the methods that we need to or override the ones we need to change.
You see inheritance every time you go to a web page. If I wrote the code for the page navigation once, I can inherit on every page that needs that navigation. This means when I make changes to the navigation class, I only have to make those changes once.
To inherit from another class, you’ll need the java keyword extends. Once you extend from another class, you can refer to each method from the parent class by name.
To override a method that already exists in the parent class, but needs to be changed for the child class. We use the same method signature, with the @override annotation, and provide a different implementation.
In the example to the right, both methods had the same method name(). The method from the child will override the parent method.
There are times where we may need access to the parent class constructor, in this case we have to use super(). This will refer to the superclass and any arguments we need to send will go inside the parenthesis.
1. You can have many levels of inheritance. Parent, child, grandchild, etc. Too many levels is bad form.
2. You cannot have multiple inheritance. We were able to implement several interfaces in the same class, but we cannot do that with inheritance.
3. We can mix interfaces & inheritance in the same class. We can extend a class and implement an interface together.
4. Multiple classes can inherit from the same parent class.
Coming soon.
Create a Parent class called Circle, and then create a child class called Cylinder that inherits Circle. Since a cylinder shares many of the same characteristics of a circle, we can reuse a lot of that functionality.
The middle rectangle tells you what global variables you will need. The minus sign is telling you to make it private.
The bottom rectangle tells you all the methods you will need. The plus sign is telling you to make it public.
Anything after a colon is the return type of that method. If the name is the same as the class, then it is the constructor.
This diagram is called a UML diagram, it is used to quickly show what information a class needs.