Typescript. Abstract classes and Interfaces

ABSTRACT CLASSES EXAMPLE
abstract class Prayer {

    abstract pray: string;

    abstract makeSins(): void;

    doPray(): string {
        return this.pray;
    }
}

class Muslim extends Prayer {

    makeSins(): void {
        console.log('sins of muslim: ', 'eating pork');
    }

    constructor(public pray: string) {  // << implemented abstract field here
        super();
    }

}

class Christian extends Prayer {

    makeSins(): void {
        console.log('sins of christian: ', 'sometimes too angry');
    }

    constructor(public pray: string) {  // << implemented abstract field here
        super();
    }

}


const christian = new Christian('Oh God');
christian.makeSins();
console.log(christian.doPray());

const aliBaba = new Muslim('Oh Allah');
aliBaba.makeSins();
console.log(aliBaba.doPray());
INTERFACES EXAMPLE
interface Believer {
believe (): string
}

class ChristianBeliever extends Christian implements Believer {

believe(): string {
return 'I believe in Jesus Christ ';
}

}

const anotherChristianBeliever = new ChristianBeliever('Oh Jesus Christ!')
anotherChristianBeliever.makeSins();
console.log(anotherChristianBeliever.believe());
console.log(anotherChristianBeliever.doPray());

SIMILAR THINGS

Both can give abstraction without implementation;

DIFFERENCES

Interfaces are clear abstraction and cannot provide fields – only methods.

Abstract classes can partially implement some methods. Also can contain fields.

This entry was posted in Без рубрики. Bookmark the permalink.