1
0

abstractとinterfaceの違い

Posted at

abstractとinterfaceの違い

  • abstract クラス:
    共通の機能を持つメソッドやプロパティの実装をする。
    継承によってその機能を拡張する場合に使います。

  • interface:
    クラスに対して 特定の契約や構造 を保証する。
    複数の契約をクラスに適用したい場合に使います。

※ interfaceは構造のみに対してabstractは共通処理も構造も定義できる

abstractの具体例

// 抽象クラスの定義
abstract class Animal {
    // 抽象メソッド(派生クラスで実装が必須)
    abstract makeSound(): void;

    // 通常のメソッド(派生クラスでも使用可能)
    eat(food: string): void {
        console.log(`The animal is eating ${food}`);
    }
}

// 抽象クラスを継承した具体的なクラス
class Dog extends Animal {
    // 抽象メソッドの実装
    makeSound(): void {
        console.log('Woof! Woof!');
    }
}

// 抽象クラスを継承した別の具体的なクラス
class Cat extends Animal {
    // 抽象メソッドの実装
    makeSound(): void {
        console.log('Meow! Meow!');
    }
}

// 抽象クラスのインスタンス化はできない
// const myAnimal = new Animal(); // エラー: 'Animal' クラスは抽象クラスです

// 具体的なクラスをインスタンス化する
const myDog = new Dog();
myDog.makeSound(); // 出力: Woof! Woof!
myDog.eat('bone'); // 出力: The animal is eating bone

const myCat = new Cat();
myCat.makeSound(); // 出力: Meow! Meow!
myCat.eat('fish'); // 出力: The animal is eating fish

interfaceの具体例

interface Animal {
    name: string;
    makeSound(): void;
    move(): void;
}

class Cat implements Animal {
    constructor(public name: string) {}

    makeSound() {
        console.log('Meow! Meow!');
    }

    move() {
        console.log(`${this.name} is moving.`);
    }
}

const myCat = new Cat('Whiskers');
myCat.makeSound(); // 出力: Meow! Meow!
myCat.move();      // 出力: Whiskers is moving.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0