JavaScript'te Inheritance, Polymorphism, Code Reuse

JavaScript, nesne yönelimli bir programlama dilidir ve nesne yönelimli programlama (OOP) prensiplerine uygun olarak, Inheritance (Kalıtım), Polymorphism (Çok Biçimlilik) ve Code Reuse (Kodun Tekrar Kullanımı) gibi kavramları destekler.

Inheritance (Kalıtım)

Kalıtım, bir nesnenin başka bir nesneden özelliklerini ve davranışlarını miras alması anlamına gelir. Bu sayede kodun tekrar kullanımı sağlanır ve daha düzenli ve esnek programlar oluşturulabilir. JavaScript'te prototip tabanlı kalıtım mevcuttur.

Örnek:

// Ana sınıf (superclass)
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  showInfo() {
    console.log(`Name: ${this.name}, Age: ${this.age}`);
  }
}

// Türetilmiş sınıf (subclass)
class Student extends Person {
  constructor(name, age, school) {
    super(name, age);
    this.school = school;
  }

  study() {
    console.log(`${this.name} is studying at ${this.school}`);
  }
}

let student1 = new Student('Alice', 20, 'ABC School');
student1.showInfo(); // Name: Alice, Age: 20
student1.study(); // Alice is studying at ABC School

Polymorphism (Çok Biçimlilik)

Polymorphism, aynı isimli fakat işlevleri farklı olan metotların aynı şekilde çağrılabilmesini ifade eder. Böylece farklı nesneleri aynı şekilde işleyebiliriz.

Örnek:

class Animal {
  makeSound() {
    console.log('Animal is making a sound');
  }
}

class Dog extends Animal {
  makeSound() {
    console.log('Dog is barking');
  }
}

class Cat extends Animal {
  makeSound() {
    console.log('Cat is meowing');
  }
}

let myPet = new Dog();
myPet.makeSound(); // Dog is barking

myPet = new Cat();
myPet.makeSound(); // Cat is meowing

Code Reuse (Kodun Tekrar Kullanımı)

JavaScript'te prototip tabanlı kalıtım ve nesne yönelimli programlama prensipleri, kodun tekrar kullanılmasını sağlar. Bir sınıfta veya objede tanımlanan özellikler ve metotlar, başka sınıflarda veya objelerde kolayca tekrar kullanılabilir.

Örnek:

class Shape {
  constructor(color) {
    this.color = color;
  }

  draw() {
    console.log(`${this.color} shape is drawn`);
  }
}

class Circle extends Shape {
  constructor(color, radius) {
    super(color);
    this.radius = radius;
  }

  calculateArea() {
    return Math.PI * this.radius * this.radius;
  }
}

let myCircle = new Circle('red', 5);
myCircle.draw(); // red shape is drawn
console.log(`Area of circle: ${myCircle.calculateArea()}`); // Area of circle: 78.54

Bu şekilde, JavaScript'te Inheritance, Polymorphism ve Code Reuse gibi OOP prensiplerini kullanarak daha organize ve esnek kodlar yazabilir ve tekrar kullanılabilir ve genişletilebilir programlar geliştirebilirsiniz.