In one of my previous articles, I wrote a little bit about encapsulation, the idea of bundling logic together. In this article, I wanted to take some time to unpack Inheritance, another Object-oriented programming (OOP) principle and what it looks like in Java.

Inheritance refers to the attributes and methods that can be passed from a parent class (superclass) to a child class (subclass). By using the extends keyword a subclass is able to inherit from the superclass.
//parent class
public class Coffee{
public Coffee(String name, double price, int numOrdered){
this.name = name;
this.price = price;
this.numOrdered = numOrdered;
}
//other super cool code here
}
public class Mocha extends Coffee{}
Take the code I wrote above for my Coffee Shop CLI application. The parent class is Coffee. In the parent, I defined the constructor which takes 3 parameters. Mocha is the child class. By using the extends keyword, I tell the compiler that there are methods and instance fields I will be pulling from the parent and building upon. I can use the super keyword to reference the parent constructor. This is what it looks like:
public Mocha(){
super("mocha", 4.99, 0);
}
Writing super is the same as writing out the constructor. The beauty of inheritance is that it saves us from writing the same code over and over again. Instead we can pull the constructor from the parent and pass the parameters that we would like our Mocha objects to contain.
Now if I were to initialize a Mocha object in the main method stored in Coffee.java and call this.name it would return the string “mocha”. You can also use super to call a method from the superclass to its subclass.
super.coolMethodHere();
Something else to note about shared information between super and subclasses is that you can use protected and final, two additional modifiers.
Check out this code block.
public class Coffee {
protected String name;
protected double price;
protected int numOrdered;
//other code here
}
Instead of using public or private when declaring the variables name, price, and numOrdered, I used protected. Declaring variables with this modifier, allows for the variables to be accessible by the subclasses only. Another class that is not Coffee’s subclass would not be able to access these variables.
By extension, variables and methods declared as final prevent changes to them. They can be accessed but the child class can’t change or overwrite the information stored in them. This helps to limit bugs that might occur if a change is made intentionally (or accidentally!).
Applying the concept of inheritance lets you build upon variables and methods as needed for your subclasses and you can also do some super cool things with Polymorphism (we’ll talk about that in another article).
You can learn more about inheritance on Oracle here.