Marcy Lab School Docs
  • Welcome
  • Student Guidelines & Policies
    • Student Handbook
    • AI Policy
    • Academic Calendar
  • Environment Setup
    • Local Environment Setup - Mac
    • Local Environment Setup - Windows
    • GitHub Setup
    • Postgres Setup
  • How-Tos
    • How To Code at Marcy: Code Style Guide
    • How to Do Short Response and Coding Assignments
    • How to Debug
    • How to PEDAC
    • How to Create A GitHub Organization and Scrumboard
    • How to Create Projects with Vite
    • How to Deploy on GitHub Pages
    • How to Deploy on Render
    • How to Test your API with Postman
  • Mod 0 - Command Line Interfaces, Git, and GitHub
    • Overview
    • 1. Command Line Interfaces
    • 2. Git & GitHub
    • 3. Git Pulling & Merging
    • 4. Git Branching & PRs
  • Mod 1 - JavaScript Fundamentals
    • Overview
    • 1. Intro to Programming
    • 2. Errors
    • 3. Node & Node Modules
    • 4. Variables, Functions & String Methods
    • 5. Control Flow, typeof, and Math
    • 6. Loops
    • 7. Arrays
    • 8. Objects
    • 9. Higher Order Functions: Callbacks
    • 10. Higher Order Functions: Array Methods
    • 11. Regex
  • Mod 2 - HTML, CSS & the DOM
    • Overview
    • 1. HTML
    • 2. CSS
    • 3. Accessibility (a11y)
    • 4. The Document Object Model (DOM) API
    • 5. Events
    • 6. Forms
    • 7. The Box Model and Positioning
    • 8. Flexbox
    • 9. Grid & Media Queries
    • 10. ESModules
    • 11. Vite
    • 12. LocalStorage
  • Mod 3 - Async & APIs
    • Overview
    • 1. Promises
    • 2. Fetch
    • 3. Building a Fetching App
    • 4. Async & Await
    • 5. A Generic Fetch Handler
  • Mod 4 - Project Week!
    • Important How Tos and Guides
      • How to Create a GitHub Organization and Scrum Board
      • How To Start a Project with Vite
      • How To Deploy a Project with GitHub Pages
    • Project Week Overview
    • Agile Methodologies
    • Deliverables & Milestones
    • Technical Requirements Checklist
    • Free API List
    • Collaborative GitHub
  • Mod 5 - Object-Oriented Programming
    • Overview
    • 1. Intro to OOP, Encapsulation, Factory Functions, and Closure
    • 2. Classes
    • 3. Private & Static
    • 4. UML Diagrams & Has Many/Belongs To Relationships
    • 5. Challenge: Implementing Has Many/Belongs To
    • 6. Inheritance
    • 7. Polymorphism
    • 8. Review and Practice
    • MDN: Object Prototypes
  • Mod 6 - Data Structures & Algorithms
    • Overview
    • Important How Tos and Guides
      • How to Debug
      • How to PEDAC
    • 1. Nodes & Linked Lists
    • 2. Singly & Doubly Linked Lists
    • 3. Stacks & Queues
    • 4. Recursion
    • 5. Trees
  • Mod 7 - React
    • Overview
    • Important How Tos and Guides
      • How to Create Projects with Vite
      • How to Deploy on GitHub Pages
    • 1. Intro to React
    • 2. Events, State, and Forms
    • 3. Fetching with useEffect
    • 4. React Router
    • 5. Building a Flashcards App
    • 6. React Context
    • 7. Global Context Pattern
  • Mod 8 - Backend
    • Overview
    • Important How Tos and Guides
      • How to Deploy on Render
      • How to Test your API with Postman
      • Postgres Setup
    • 1. Intro to Express
    • 2. Building a Static Web Server with Middleware
    • 3. Securing API Keys and Environment Variables
    • 4. RESTful CRUD API
    • 5. Model-View-Controller Architecture
    • 6. SQL and Databases
    • 7. JOIN (Association) SQL Queries
    • 8. Knex
    • 9. Your First Fullstack App!
    • 10. Migrations & Seeds
    • 11. Schema Design & Normalization
    • 12. Hashing Passwords with Bcrypt
    • 13. React Express Auth Template Overview
  • Mod 9 - Civic Tech Hackathon
    • Overview
    • Rubric
  • Mod 10 - Capstone
    • Overview
Powered by GitBook
On this page
  • Inheritance and "Is A" Relationships
  • Array is a Subclass of Object
  • Establishing Inheritance Between Custom Classes
  • Extends and Super
  • Refactor Challenge
  • Summary
  1. Mod 5 - Object-Oriented Programming

6. Inheritance

Previous5. Challenge: Implementing Has Many/Belongs ToNext7. Polymorphism

Last updated 3 months ago

Follow along with code examples !

Table of Contents:

Inheritance and "Is A" Relationships

Inheritance is a pillar of object-oriented programming. It describes a relationship between two classes: a subclass that inherits methods from a superclass. As a result, instances of the sub-class can use methods defined in a super-class.

We call this an "Is A" relationship

Question: Using the terms "subclass" and "superclass", what is the inheritance relationship between the Professor class and the Person class? What about the GraduateStudent class and the Person class?

Both Professor and GraduateStudent are subclasses of the Person class.

Array is a Subclass of Object

The Array class is a sub-class of the Object class which is the super-class.

Every Array instance gets methods from the Array.prototype which inherits methods from the Object.prototype. Therefore, all arrays can use Object.prototype methods like toString().

Try running the following code:

const arr = [1,2,3];

console.log(arr.toString());
console.log(arr); // expand the prototype chain to find the .toString() method

console.log(typeof arr); 
console.log(arr instanceof Array);
console.log(arr instanceof Object);

Establishing Inheritance Between Custom Classes

Imagine we have a Person class. I want to make another class called Programmer that can do everything a Person can, with some additional properties and behaviors that only instances of Programmer will have.

How NOT to do it:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
    this.friends = [];
  }
  makeFriend(friend) {
    this.friends.push(friend)
    console.log(`Hi ${friend}, my name is ${this.name}, nice to meet you!`);
  }
  doActivity(activity) {
    console.log(`${this.name} is ${activity}`);
  }
}

class Programmer {
  constructor(name, age, language) {
    this.name = name;
    this.age = age;
    this.friends = [];
    this.favoriteLanguage = language;
  }
  makeFriend(friend) {
    this.friends.push(friend)
    console.log(`Hi ${friend}, my name is ${this.name}, nice to meet you!`);
  }
  doActivity(activity) {
    console.log(`${this.name} is ${activity}`);
  }
  code() {
    this.doActivity(`writing some ${this.favoriteLanguage} code.`);
  }
}
Question: What bad practice exists this code?

This code breaks the DRY rule (Don't Repeat Yourself). Much of the code in Programmer is the same as the code in Person. Wouldn't it be great for Programmer to automatically inherit the makeFriend and doActivity methods?

Extends and Super

To remove the repetitive code AND to establish a relationship between Programmer and Person, we use the extends and super keywords to define our Programmer class:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
    this.friends = [];
  }
  makeFriend(friend) {
    this.friends.push(friend)
    console.log(`Hi ${friend}, my name is ${this.name}, nice to meet you!`);
  }
  doActivity(activity) {
    console.log(`${this.name} is ${activity}`);
  }
}

class Programmer extends Person {
  constructor(name, age, language) {
    super(name, age);                 // invoke the Person constructor, setting the name, age, and friends properties on `this`
    this.favoriteLanguage = language; // add a favoriteLanguage property only for Programmers
  }
  
  // makeFriend is inherited
  // doActivity is inherited
  
  code() { // a new method only Programmer instances can use
    this.doActivity(`writing some ${this.favoriteLanguage} code.`);
  }
}

Refactor Challenge

Create another subclass called WebDeveloper that extends the Programmer class. It should have its favoriteLanguage be set to "JavaScript" by default.

Add a deploy method to the WebDeveloper class that leverages the inherited doActivity method to print out a message saying [Name] is deploying.

Then, with a partner, discuss these questions:

Question 1: What does extends do?

extends makes the WebDeveloper inherit methods from Programmer. It sets Programmer.prototype as the prototype for WebDeveloper

Question 2: What does super do?

super() invokes the Programmer constructor function using its own value of this. Any properties that the Programmer constructor sets on this will be set on WebDeveloper.

Question 3: What do we know about the relationship between a Programmer and a Person?
  • WebDeveloper is said to be a subclass of Programmer.

  • Programmer is said to be a superclass of WebDeveloper.

  • WebDeveloper will inherit properties and methods from Programmer and Person.

  • Instances of WebDeveloper are also instances of Programmer and of Person, but not all instances of Person or Programmer are instances of WebDeveloper.

Question 4: How does the code method work?

code invokes the doActivity method inherited from Person.prototype

Summary

  • Inheritance occurs when a child class inherits properties and methods from a parent class

    • The extends keyword creates this relationship

    • The super keyword references the parent class

    • You can invoke super() to invoke the parent class constructor.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
    this.friends = [];
  }
  makeFriend(friend) {
    this.friends.push(friend)
    console.log(`Hi ${friend}, my name is ${this.name}, nice to meet you!`);
  }
  doActivity(activity) {
    console.log(`${this.name} is ${activity}`);
  }
}

class Programmer extends Person {
  constructor(name, age, language) {
    super(name, age);                 // invoke the Person constructor, setting the name, age, and friends properties on `this`
    this.favoriteLanguage = language; // add a favoriteLanguage property only for Programmers
  }
  
  // makeFriend is inherited
  // doActivity is inherited
  
  code() { // a new method only Programmer instances can use
    this.doActivity(`writing some ${this.favoriteLanguage} code.`);
  }
}
here
Inheritance and "Is A" Relationships
Array is a Subclass of Object
Establishing Inheritance Between Custom Classes
Extends and Super
Refactor Challenge
Summary
A Person class sits at the top of the "tree". A Doctor, a Professor, and a Student class sit below and all inherit from the Person class. A GraduateStudent class inherits from the Student class.