Skip to content

Instantly share code, notes, and snippets.

@sannimichaelse
Created November 19, 2018 15:42
Show Gist options
  • Save sannimichaelse/39fb5596aad7cdc837d0a175051931c0 to your computer and use it in GitHub Desktop.
Save sannimichaelse/39fb5596aad7cdc837d0a175051931c0 to your computer and use it in GitHub Desktop.
Demonstrating Knowledge of OOP using Inheritance, Polymorphism, and Encapsulation
/*****
INHERITANCE
******/
class AnimalKingdom {
constructor(name){
this.speed = 0;
this.name = name;
}
run(distance,time){
this.speed = distance/time;
console.log(`I am a ${this.name}. I am currently running with a speed of ${this.speed}ms-1.`);
}
stop(){
this.speed = 0;
console.log(`${this.name} stopped.`);
}
}
// Inherit from AnimalKingdom
class Cheetah extends AnimalKingdom {
hide() {
console.log(`${this.name} hides! because he saw a Lion Approaching`);
}
}
let cheetah = new Cheetah("cheetah");
cheetah.run(10,2); // cheetah inherits run from the Animalkingdom
cheetah.hide(); // cheetah hides!
console.log('#############')
console.log('#############')
/*****
POLYMORPHISM - Method Overidding
******/
class President {
constructor(name){
this.name = name;
this.presidentAdvice = 'ADVICE - I am Buhari,Vote and Get A million Naira'
}
right() {
console.log(`RIGHT - I am ${this.name}. As a citizen i have the right to choose who i vote for `);
}
opinion(text){
console.log(`OPINION - My name is ${this.name}. ${text}`);
}
advice(){
console.log(this.presidentAdvice);
}
}
// Inherit from AnimalKingdom
class VicePresident extends President {
advice(){
console.log(`ADVICE - Vote for me ${this.name}. I will give you 2 Million `)
}
}
let vp = new VicePresident("Osinbajo");
let text = 'I am not voting for Buhari, this year period'
vp.right();
vp.opinion(text)
vp.advice(); // Osinbajo is overriding buhari's Advice
console.log('#############')
console.log('#############')
/*****
ENCAPSULATION
******/
class Calculator {
constructor(name,age){
var minAge = 20
this.name = name;
this.age = age;
}
getAge(){
return this.age;
}
getAgeSum(){
return this.getAge() + this.minAge;
}
}
// Calculator
class AgeCalculator extends Calculator {
print() {
console.log(`My name is ${this.name}. Cummulative age is ${this.getAgeSum()}`);
}
}
let user = new AgeCalculator('mikel',10);
user.print()
console.log('User Age = '+user.getAge());
console.log(user.minAge) // Undefined - You should not be able to get min age
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment