MD10
MD10

Reputation: 1521

executing method of a class that extends an abstract class

I have encountered this example from Typescript site:

abstract class Department {

    constructor(public name: string) {
    }

    printName(): void {
        console.log("Department name: " + this.name);
    }

    abstract printMeeting(): void; // must be implemented in derived classes
}

class AccountingDepartment extends Department {

    constructor() {
        super("Accounting and Auditing"); // constructors in derived classes must call super()
    }

    printMeeting(): void {
        console.log("The Accounting Department meets each Monday at 10am.");
    }

    generateReports(): void {
        console.log("Generating accounting reports...");
    }
}

let department: Department; // ok to create a reference to an abstract type
department = new Department(); // error: cannot create an instance of an abstract class
department = new AccountingDepartment(); // ok to create and assign a non-abstract subclass
department.printName();
department.printMeeting();
**department.generateReports();** // error: method doesn't exist on declared abstract type???

I have 2 questions regarding this:

  1. why this line is not valid ? department has access to generateReports() since it's type is also Acounting Department. I have run this code and it indeed executes department.generateReports() with no problem

  2. when I am doing department = new Department(); although this is a mistake to create an instance of an abstract class it doesnt give me a runtime error. Why is this happening ? Is this is my responsibility to not create an instance of an abstract class?

Upvotes: 0

Views: 106

Answers (1)

leonardfactory
leonardfactory

Reputation: 3501

  1. department is declared to be a Departement, this means that even if it could be an AccountingDepartement, it's not assured to be. Just think about that:

    let department: Department;
    // ...
    department = departmentName === 'accounting'
      ? new AccountingDepartment()
      : new CustomerCareDepartment();
    // ...
    department.generateReports(); // You really can't know if it's available
    

    If you just typed let department = new AccountingDepartment(); it would have been ok, since TS infers type and declares department as an AccountingDepartment

  2. Abstract classes are a TypeScript feature, not JS, so when TS is transpiled to JS, the abstract keyword is just removed. You will get errors at compile time, like most of the TypeScript features, not at compile time. See a transpilation example here: Playground Link

Upvotes: 1

Related Questions