This is the 18th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Class inheritance introduction
What are the benefits of using class inheritance?
Inheritance is an important feature of object orientation.
With inheritance, a subclass can have the features and capabilities of its parent class without additional code, and can extend the parent class to increase code reusability.
Next, let’s learn about inheritance in TS.
Class inheritance
Inheritance is a very important concept in object orientation. If a subclass inherits from a parent class, it has the attributes and methods of the parent class.
This mechanism of inheritance can enhance the reusability of code by abstracting the properties and methods common to subclasses. At the same time, for some inconsistent subclasses, we can override the properties or methods of the parent class in the subclass by means of carbon copy. In this example, we define:
/ / parent class
class Animal {
name: string;
sayHi() {
console.log('Hi'); }}/ / subclass
class Cat extends Animal {
sayHi() {
console.log(`Meow, my name is The ${this.name}`);
}
catchMouse() {
console.log('Caught a mouse'); }}Copy the code
In this case, we define the parent Animal, which has the name property and the sayHi method, and then we define a subclass Cat, which inherits from the parent, so that Cat also has the name property and the sayHi method, and then we define the sayHi method on Cat, In this case, the method overrides the sayHi method of the parent class. In addition, the Cat has some unique methods: the catchMouse method.
Problem: What is the result of the following expression?
class Animal {
protected age = 10;
public getAge() {
return this.age; }}class Panda extends Animal {
setAge(age: number) {
return this.age = age; }}const p = new Panda();
p.getAge(); / / the result?
p.setAge(20); / / the result?
Copy the code
Answer: 10, 20
Resolution:
A class (A) can inherit from another class (B) using extends. We call class A A subclass and class B A parent.
A subclass will have all the attributes and methods of the parent class, and the same attributes or methods in the subclass will override the parent class. If a constructor exists in a subclass, the subclass’s constructor needs to have a super call from the parent class, that is, the constructor that calls the parent class.
Subclass Panda inherits from Animal, so there is an age attribute anda getAge method in the instance object P of subclass Panda. So the result of p.age () is 10, and the result of p.age (20) is 20.