geekelo / geekelo/dsa_practice
Practice designing class hierarchies and relationships.
- Dominant language
- No language data
- Stars
- 1
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
Certainly! Designing class hierarchies and relationships is an important aspect of object-oriented programming. Let's go through a simple example to illustrate this concept. We'll design a class hierarchy for a zoo simulation.
### Zoo Simulation Example:
```javascript
// Animal class as the base class
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
makeSound() {
console.log(`${this.name} says ${this.sound}`);
}
}
// Mammal class extends Animal
class Mammal extends Animal {
constructor(name, sound, furColor) {
super(name, sound);
this.furColor = furColor;
}
walk() {
console.log(`${this.name} is walking.`);
}
}
// Bird class extends Animal
class Bird extends Animal {
constructor(name, sound, featherColor) {
super(name, sound);
this.featherColor = featherColor;
}
fly() {
console.log(`${this.name} is flying.`);
}
}
// Reptile class extends Animal
class Reptile extends Animal {
constructor(name, sound, scaleType) {
super(name, sound);
this.scaleType = scaleType;
}
crawl() {
console.log(`${this.name} is crawling.`);
}
}
// Zoo class that aggregates different animals
class Zoo {
constructor() {
this.animals = [];
}
addAnimal(animal) {
this.animals.push(animal);
}
performDailyActivities() {
console.log("Daily activities at the zoo:");
this.animals.forEach(animal => {
if (animal instanceof Mammal) {
animal.walk();
} else if (animal instanceof Bird) {
animal.fly();
} else if (animal instanceof Reptile) {
animal.crawl();
}
animal.makeSound();
});
}
}
// Usage
const lion = new Mammal("Lion", "Roar", "Golden");
const parrot = new Bird("Parrot", "Squawk", "Colorful");
const snake = new Reptile("Snake", "Hiss", "Smooth");
const zoo = new Zoo();
zoo.addAnimal(lion);
zoo.addAnimal(parrot);
zoo.addAnimal(snake);
zoo.performDailyActivities();
```
In this example:
- `Animal` is the base class with common properties and methods.
- `Mammal`, `Bird`, and `Reptile` extend the `Animal` class, inheriting its properties and methods while adding their specific attributes.
- `Zoo` is a class that aggregates instances of different animals and can perform daily activities for each type of animal.
This example demonstrates class hierarchies, inheritance, and polymorphism. Designing your class hierarchies thoughtfully can lead to more modular and maintainable code.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.