Inheritance Basics
Inheritance is a core concept in object-oriented programming, allowing you to create new classes based on existing ones. In TypeScript, inheritance is implemented using the extends keyword. When you define a class that extends another, the new class is called a derived class (or subclass), and the class it is based on is called the base class (or superclass). The derived class automatically inherits all public and protected properties and methods from the base class, which means you can reuse code and build logical hierarchies in your applications.
123456789101112131415161718192021222324class Animal { name: string; constructor(name: string) { this.name = name; } speak(): void { console.log(`${this.name} makes a noise.`); } } class Dog extends Animal { constructor(name: string) { super(name); } speak(): void { console.log(`${this.name} barks.`); } } const myDog = new Dog("Rex"); myDog.speak(); // Output: Rex barks.
By using inheritance, you can avoid duplicating code across classes that share common behavior. For example, the Dog class inherits the name property and the speak method from the Animal class, but can also define or override its own methods. This structure makes it easier to organize code, maintain large codebases, and represent real-world relationships between entities using a class hierarchy.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 5
Inheritance Basics
Svep för att visa menyn
Inheritance is a core concept in object-oriented programming, allowing you to create new classes based on existing ones. In TypeScript, inheritance is implemented using the extends keyword. When you define a class that extends another, the new class is called a derived class (or subclass), and the class it is based on is called the base class (or superclass). The derived class automatically inherits all public and protected properties and methods from the base class, which means you can reuse code and build logical hierarchies in your applications.
123456789101112131415161718192021222324class Animal { name: string; constructor(name: string) { this.name = name; } speak(): void { console.log(`${this.name} makes a noise.`); } } class Dog extends Animal { constructor(name: string) { super(name); } speak(): void { console.log(`${this.name} barks.`); } } const myDog = new Dog("Rex"); myDog.speak(); // Output: Rex barks.
By using inheritance, you can avoid duplicating code across classes that share common behavior. For example, the Dog class inherits the name property and the speak method from the Animal class, but can also define or override its own methods. This structure makes it easier to organize code, maintain large codebases, and represent real-world relationships between entities using a class hierarchy.
Tack för dina kommentarer!