M
M
Maxim Ivanov2017-03-16 00:14:22
typescript
Maxim Ivanov, 2017-03-16 00:14:22

How to correctly override a method in a child class?

I have a stupid situation, but I will give an example-synonymous with my code

class Parent {

  constructor(){
   
  }


  methodA(){
    // ..
    this.methodB();
    // ..
  }

  methodB(){
   // empty because need override in child class 
  }


};


class Child1 extends Parent {

  constructor(){
    super();
  }

  methodB(){
   // my actions
  }

}

I have a lot of such child classes, and they are inherited from the parent class that has method A (it’s dreary to prescribe it in each child class, there are a lot of actions going on inside), but it calls method B, the internal method B for each child class has its own ( Child1, Child2, .., ChildN), but if I do not register it in the parent class (then the compiler swears and says that it does not see it), what should I do? Somehow it looks ugly when I leave an empty method in the parent class.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Korolev, 2017-03-16
@splincodewd

The first option is to make the parent class abstract and declare an abstract method methodB in it. The compiler will require that methodB must be declared in the descendant class

abstract class Parent {
  methodA(){
    this.methodB();
  }

  abstract methodB(): void
};

class Child1 extends Parent { // Ошибка: Non-abstract class 'Child1' does not implement inherited abstract member 'methodB' from class 'Parent'.
  constructor(){
    super();
  }
}

If it is not possible to declare the parent class as abstract, you can declare the method methodB inside it and throw an exception in it, saying that this method must be redeclared in the child. So the error will be caught only at runtime, but it's better than nothing.
PS: But in general, relying on child methods in the parent is not a good practice =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question