Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Javascript Encapsulation Inheritance Polymorphism Composition

class Animal {
  eat() {
    return "Rax eat";
  }
}

class Dog extends Animal {
  sound() {
    return "Dog barks";
  }
}

class Cat extends Animal {
  sound() {
    return "Cat meows";
  }
}

class Home {
  constructor() {
    this.pets = []; // Could be a `new Set` for better efficiency
  }
  adoptPet(animal) {
    if (this.pets.includes(animal)) {
      throw new Error("Cannot adopt the same pet twice");
    }
    this.pets.push(animal);
  }
  makeAllSounds() {
    for (let pet of this.pets) {
      console.log(pet.sound());
    }
  }
}

var home = new Home();
var dog1 = new Dog();
var dog2 = new Dog();
var cat = new Cat();

home.makeAllSounds(); // this doesn't give/return any result/data
console.log("== Adding dog ==");
home.adoptPet(dog1);
home.makeAllSounds(); // this prints: Dog barks
console.log("== Adding cat ==");
home.adoptPet(cat);
home.makeAllSounds(); // this prints : Dog barks / Cat meows
console.log("== Adding dog ==");
home.adoptPet(dog2);
home.makeAllSounds(); // ...
home.adoptPet(dog1) // not ok!
 Run code snippet
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Javascript #Encapsulation #Inheritance #Polymorphism #Composition
ADD COMMENT
Topic
Name
5+4 =