In addition to the inherited features, child classes can contain their own properties, getters, setters, and methods.
Below, we will add a usesLitter
getter. The syntax for creating getters, setters, and methods is the same as it is in any other class.
class Cat extends Animal { constructor(name, usesLitter) { super(name); this._usesLitter = usesLitter; } get usesLitter() { return this._usesLitter; } }
In the example above, we create a usesLitter
getter in the Cat
class that returns the value saved to _usesLitter
.
Compare the Cat
class above to the one we created without inheritance:
class Cat { constructor(name, usesLitter) { this._name = name; this._usesLitter = usesLitter; this._behavior = 0; } get name() { return this._name; } get usesLitter() { return this._usesLitter; } get behavior() { return this._behavior; } incrementBehavior() { this._behavior++; } }
We decreased the number of lines required to create the Cat
class by about half. Yes, it did require an extra class (Animal
), making the reduction in the size of our Cat
class seem moot. However, the benefits (time saved, readability, efficiency) of inheritance grow as the number and size of your subclasses increase.
One benefit is that when you need to change a method or property that multiple classes share, you can change the parent class, instead of each subclass.
Before we move past inheritance, take a moment to see how we would create an additional subclass, called Dog
.
class Dog extends Animal { constructor(name) { super(name); } }
This Dog
class has access to the same properties, getters, setters, and methods as the Dog
class we made without inheritance, and is a quarter the size.
Now that we’ve abstracted animal daycare features, it’s easy to see how you can extend Animal
to support other classes, like Rabbit
, Bird
or even Snake
.
Instructions
Use the properties and methods below to help you complete the tasks that follow.
Nurse
- Properties:
_name
,_remainingVacationDays
(set to20
inside theconstructor()
),_certifications
- Methods:
.takeVacationDays()
,.addCertification()
Under the Nurse constructor()
, add a getter that returns the value saved to the Nurse instance’s _certifications
.
Add a method called addCertification
under the certifications
getter.
The method should accept one input (newCertification
). Inside the method, use the push method to add the newCertification
value to the nurse’s certifications
array.
At the bottom of main.js call the .addCertification()
method on nurseOlynyk
with a parameter of 'Genetics'
.
Log the value saved to the certifications
property of nurseOlynyk
.