How to set them up + inheritance through parent classes
What are classes used for?
Classes are a tool that developers use to quickly create instances of objects. They’re a great way to keep your code DRY and to reduce the chances of repetitive code. Let’s say that you are running a summer camp, and want an easy way to organize the data of all your different campers. Below is an example of a Camper class, and later on in the article, we will discuss how to navigate inheritance with “parent” classes.
Let’s break this down!
- Camper — Camper is the name of the class, and classes are conventionally written in CamelCase.
- Constructor — this constructor method will invoke any time a new instance of Camper is created, and it will be initiated with a name and an age. Example: const newCamper = new Camper(“Sara”, 10). You are then able to log this new instance like so: console.log(newCamper.name) to return Sara.
- Within the constructor method, we use the this keyword to refer back to the instance of that class.
Within the classes, you can set up any getter methods that you think are relevant in order to create some sort of behavior within your class, or to manipulate data. For example, you can simply create a method that returns the name of a Camper, the syntax being the same as any object you would create.
However, let’s say that we want to expand our Campers. We wanted to create an extra set of organization, and we want to separate our Camper class into Volunteers and Kids. In order to do so (again, without repeating code and keeping it DRY), we can use implement our existing Camper class to be the parent class (aka superclass), and our Volunteer and Kid class to be the child classes (aka subclasses). In other words, our child classes will inherit the properties from the parent class (name, age), as well as any methods from the parent class. However, let’s say your Volunteer class has an extra property that is not part of your parent Camper class.
You may notice some new keywords above that we didn’t see before. Let’s break them down:
- extends — this will make the methods of the “superclass” (Camper) available in the “subclass” (Volunteer). You will set up the constructor as normal.
- super — the super keyword will call the constructor of the parent class, in our case name and age, followed by any new properties unique to that subclass, in this case yearsVolunteering.
Lastly, we will discuss static methods. Static methods are methods that can be called from the class, but aren’t tied to any specific instances within that class. For example:
Because of the keyword, we can only call the .returnCamper() method on the parent class, and not on any instances of the parent class.