Wednesday, November 14, 2018

TypeScript - Classes - abstract classes

Abstract classes are classes which cannot be instantiated. They serve as base class from which other classes may be derived.

Consider that we want to create an abstract class for Fighter Planes:

// Abstract Classes
abstract class FighterPlanes {
manufacturerName: string = "Dassault Aviation";
budget: number = 30000;

abstract changeName(name:string) : void;
calcBudget(){
return this.budget *2;
}
}

Now, if we want to extend this class to a specific plane. The above abstract class will be a default template for all the future Fighter Planes.

class B2Spirit extends FighterPlanes {
changeName(name:string): void {
this.manufacturerName = name;
}
}

Let us instantiate this child class and save the file.

let newProject = new B2Spirit ();
console.log(newProject);
console.log(newProject.changeName("Northrop Grumman"));
console.log(newProject);


Compiling the project:

$ tsc
$

Start the Local Server:

$ python -m SimpleHTTPServer 3000
$

Check the console in the Web Browser:

B2Spirit {manufacturerName: "Dassault Aviation", budget: 30000}
city-App.ts:196 undefined
city-App.ts:197 B2Spirit {manufacturerName: "Northrop Grumman", budget: 30000}


Reference:

No comments:

Post a Comment