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

1
  • 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. Commented Oct 3, 2018 at 16:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

that was a deep dive in to the OO inheritance, thank you for the detailed response. It was much helpful
Just avoid calling child methods from base class constructor. While it's technically possible, it's still not recommended, since it may lead to problems related to initialization order.
@AlexChe -- Yes, of course :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.