0

I am using inheritance to split the logic through base and derived class.

In the following case scenario:

export class FirstClass{
constructor(){}

//consoleGivenMessage('dummy text');}

export class SecondClass extends FirstClass{
constructor(){
    super();
}

consoleGivenMessage(text:string){
    console.log(text);
}}

what is the way to call the function from the base class? Should the "consoleGivenMessage(text:string)" been implemented in the base class as well?

Any help is welcome

George George
  • 571
  • 3
  • 7
  • 18
  • 1
    What do you mean call it from the base class? Yes you would have to define it in the base class ... I think we need more information about what you're trying to do. – Explosion Pills Oct 03 '18 at 16:15

1 Answers1

1

The short answer to your question is, you have to implement consoleGivenMessage(text: string) in FirstClass so that you can call it on instances of both FirstClass and SecondClass.

However, there is more--

Most of the time, you call an inherited method from the derived class instead of the other way round. But, you can also have a base class that depends on an abstract method that is implemented in a derived class.

Say, you have a class A that depends on a method DoIt() which is implemented only in derived class B, you would have to declare A as an abstract class and DoIt() as an abstract method; then, in B (which is not abstract--that is, it is concrete) you would implement the method DoIt().

This also means that you cannot instantiate an object of A because it is not complete without a full implementation of DoIt, but you can instantiate an object of B. However, you can define an object of A, like this: const a: A = new B(). And, you can call a.DoIt(). In this case, the implementation of B.DoIt() would actually be called.

This technique is used in the Template Method design pattern.

TypeScript classes, inheritance, and abstract classes are well documented.

RWRkeSBZ
  • 723
  • 4
  • 11
  • 1
    that was a deep dive in to the OO inheritance, thank you for the detailed response. It was much helpful – George George Oct 04 '18 at 06:39
  • 1
    Just avoid calling child methods from base class constructor. While it's technically possible, it's still [not recommended](https://stackoverflow.com/a/47821096/23715), since it may lead to problems related to initialization order. – Alex Che Feb 15 '22 at 10:27
  • @AlexChe -- Yes, of course :-) – RWRkeSBZ Feb 16 '22 at 21:47