- 4 years ago
- Afaq Arif
- 2,837 Views
-
4
In this chapter, we will discuss classes in TypeScript in detail. We will also study the inheritance of classes in TypeScript.
TypeScript is an object-oriented JavaScript carrying object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a design for making objects. It sums up the data for the object. Typescript gives built-in support for this idea called class. JavaScript ES5 or earlier didn’t support classes. Typescript gets this feature from ES6.
Creating classes
You can use the class keyword to state a class in TypeScript. The syntax for the same is given below.
Syntax
class class_name {
//class scope
}
The class keyword must follow the class name. You should also consider the rules for identifiers while naming a class.
A class definition includes the following.
- Fields − A field is any variable state in a class. They represent data concerning objects.
- Constructors − They are responsible for assigning memory for the objects of the class.
- Functions − Functions show actions an object can take. They are also at times related to as methods.
When you put these components together, they are termed as the data members of the class.
Consider a class Person in typescript.
It runs following JavaScript code on composing.
//Generated by typescript 1.8.10
var Person = (function () {
function Person() {
}
return Person;
}());
Example: Declaring a class
class Car {
//field
engine:string;
//constructor
constructor(engine:string) {
this.engine = engine
}
//function
disp():void {
console.log("Engine is : "+this.engine)
}
}
The example states a class Car having a field named engine. The var keyword is not used while maintaining a field. The example above represents a constructor for the class.
A constructor is a special function of the class. It is responsible for initializing the variables of the class. You can define a constructor using the constructor keyword in TypeScript. A constructor is a function and so can be restricted.
This keyword points to the current example of the class. We have the same name here for the parameter name and the name of the class’s field. The class’s field is prefixed with this keyword in order to avoid any uncertainty.
disp() is a simple function definition. Note that the function keyword is not used here.
The following JavaScript code will run on composing.
//Generated by typescript 1.8.10
var Car = (function () {
//constructor
function Car(engine) {
this.engine = engine;
}
//function
Car.prototype.disp = function () {
console.log("Engine is : " + this.engine);
};
return Car;
}());
Creating Instance objects
You can create an instance of the class by using the new keyword followed by its name. The syntax for the same is given below.
Syntax
var object_name = new class_name([ arguments ])
- The new keyword is responsible for instantiation.
- The right-hand side of the expression calls on the constructor. The constructor should be passed values if it is restricted.
Example: Instantiating a class
var obj = new Car("Engine 1")
Accessing Attributes and Functions
You can get the features and functions of a class through the object. We use the ‘ . ’ dot notation (called as the period) to obtain data members of a class.
//accessing an attribute
obj.field_name
//accessing a function
obj.function_name()
Example: Putting them together
class Car {
//field
engine:string;
//constructor
constructor(engine:string) {
this.engine = engine
}
//function
disp():void {
console.log("Function displays Engine is : "+this.engine)
}
}
//create an object
var obj = new Car("XXSY1")
//access the field
console.log("Reading attribute value Engine as : "+obj.engine)
//access the function
obj.disp()
It runs following JavaScript code on composing.
//Generated by typescript 1.8.10
var Car = (function () {
//constructor
function Car(engine) {
this.engine = engine;
}
//function
Car.prototype.disp = function () {
console.log("Function displays Engine is : " + this.engine);
};
return Car;
}());
//create an object
var obj = new Car("XXSY1");
//access the field
console.log("Reading attribute value Engine as : " + obj.engine);
//access the function
obj.disp();
The output of the above code is as follows.
Reading attribute value Engine as : XXSY1
Function displays Engine is : XXSY1
Class Inheritance
TypeScript carries the idea of Inheritance. Inheritance is the ability of a program to create new classes from an existing class. The class that is extended to create newer classes is called the parent class/super class. The newly created classes are called the child/sub classes.
We use the ‘extends’ keyword to obtain a class from another class. The child classes have all properties and methods except private members and constructors from the parent class.
Syntax
class child_class_name extends parent_class_name
However, TypeScript doesn’t support multiple inheritance.
Example: Class Inheritance
class Shape {
Area:number
constructor(a:number) {
this.Area = a
}
}
class Circle extends Shape {
disp():void {
console.log("Area of the circle: "+this.Area)
}
}
var obj = new Circle(223);
obj.disp()
On composing. it shows following JavaScript code.
//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Shape = (function () {
function Shape(a) {
this.Area = a;
}
return Shape;
}());
var Circle = (function (_super) {
__extends(Circle, _super);
function Circle() {
_super.apply(this, arguments);
}
Circle.prototype.disp = function () {
console.log("Area of the circle: " + this.Area);
};
return Circle;
}(Shape));
var obj = new Circle(223);
obj.disp();
The output of the above code is as follows.
The above example states a class Shape extended by the Circle class. Since there is an inheritance relationship between the classes, the child class i.e. the class Car gets absolute way to its parent class property i.e. area.
We can classify Inheritance as below.
- Single − Every class can at the most extend from one parent class.
- Multiple − A class can obtain from multiple classes. TypeScript doesn’t carry multiple inheritances.
- Multi-level − The following example shows how multi-level inheritance works.
Example
class Root {
str:string;
}
class Child extends Root {}
class Leaf extends Child {} //indirectly inherits from Root by virtue of inheritance
var obj = new Leaf();
obj.str ="hello"
console.log(obj.str)
The class Leaf gets the attributes from Root and Child classes by virtue of multi-level inheritance.
It runs following JavaScript code on composing.
//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Root = (function () {
function Root() {
}
return Root;
}());
var Child = (function (_super) {
__extends(Child, _super);
function Child() {
_super.apply(this, arguments);
}
return Child;
}(Root));
var Leaf = (function (_super) {
__extends(Leaf, _super);
function Leaf() {
_super.apply(this, arguments);
}
return Leaf;
}(Child));
var obj = new Leaf();
obj.str = "hello";
console.log(obj.str);
Its output is as follows.
Output
TypeScript ─ Class inheritance and Method Overriding
Method Overriding is a process by which the child class redefines the superclass’s method. The following example shows the same.
class PrinterClass {
doPrint():void {
console.log("doPrint() from Parent called…")
}
}
class StringPrinter extends PrinterClass {
doPrint():void {
super.doPrint()
console.log("doPrint() is printing a string…")
}
}
var obj = new StringPrinter()
obj.doPrint()
The super keyword points to the immediate parent of a class. The keyword can be used to relate to the super class version of a variable, property, or method. Line 13 calls on the super class version of the doWork() function.
On composing, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var PrinterClass = (function () {
function PrinterClass() {
}
PrinterClass.prototype.doPrint = function () {
console.log("doPrint() from Parent called…");
};
return PrinterClass;
}());
var StringPrinter = (function (_super) {
__extends(StringPrinter, _super);
function StringPrinter() {
_super.apply(this, arguments);
}
StringPrinter.prototype.doPrint = function () {
_super.prototype.doPrint.call(this);
console.log("doPrint() is printing a string…");
};
return StringPrinter;
}(PrinterClass));
var obj = new StringPrinter();
obj.doPrint();
The output of the above code is as follows.
doPrint() from Parent called…
doPrint() is printing a string…
The static Keyword
You can use the static keyword to the data members of a class. A static variable can hold its values till the program ends running. Static members are referenced by the class name.
Example
class StaticMem {
static num:number;
static disp():void {
console.log("The value of num is"+ StaticMem.num)
}
}
StaticMem.num = 12 // initialize the static variable
StaticMem.disp() // invoke the static method
The following JavaScript code runs on composing.
//Generated by typescript 1.8.10
var StaticMem = (function () {
function StaticMem() {
}
StaticMem.disp = function () {
console.log("The value of num is" + StaticMem.num);
};
return StaticMem;
}());
StaticMem.num = 12; // initialize the static variable
StaticMem.disp(); // invoke the static method
The output of the above code is as follows.
The instanceof operator
The instanceof operator returns true if the object belongs to the specified type.
Example
class Person{ }
var obj = new Person()
var isPerson = obj instanceof Person;
console.log(" obj is an instance of Person " + isPerson);
On composing, it runs following JavaScript code.
//Generated by typescript 1.8.10
var Person = (function () {
function Person() {
}
return Person;
}());
var obj = new Person();
var isPerson = obj instanceof Person;
console.log(" obj is an instance of Person " + isPerson);
The output of the above code is as follows.
obj is an instance of Person True
Data Hiding
A class can control the visibility of its data members to members of other classes. This ability is termed Data Hiding or Encapsulation.
Object Orientation uses the idea of access modifiers or access specifiers to execute the concept of Data Hiding. The access specifiers/modifiers define the visibility of a class’s data members outside its defining class.
The access modifiers supported by TypeScript are as follows.
S.No. | Access Specifier & Description |
---|
1. | public A public data member has universal accessibility. The data members in a class are public by default. |
2. | private Private data members are accessible only within the class that defines these members. If an external class member tries to access a private member, the compiler gives an error. |
3. | protected A protected data member is available by the members within the same class as that of the former and also by the members of the child classes. |
Example
Let us now take an example to see how data hiding works.
class Encapsulate {
str:string = "hello"
private str2:string = "world"
}
var obj = new Encapsulate()
console.log(obj.str) //accessible
console.log(obj.str2) //compilation Error as str2 is private
The class has two string attributes, str1 and str2, which are public and private members respectively. The class is symbolized. The example returns a compile-time error, as the private attribute str2 is reached outside the class that states it.
Classes and Interfaces
Classes can also apply interfaces.
interface ILoan {
interest:number
}
class AgriLoan implements ILoan {
interest:number
rebate:number
constructor(interest:number,rebate:number) {
this.interest = interest
this.rebate = rebate
}
}
var obj = new AgriLoan(10,1)
console.log("Interest is : "+obj.interest+" Rebate is : "+obj.rebate )
The class AgriLoan applies for the interface Loan. So, it is now forcing on the class to add the property interest as its member.
On composing, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var AgriLoan = (function () {
function AgriLoan(interest, rebate) {
this.interest = interest;
this.rebate = rebate;
}
return AgriLoan;
}());
var obj = new AgriLoan(10, 1);
console.log("Interest is : " + obj.interest + " Rebate is : " + obj.rebate);
The output of the above code is as follows.
Interest is : 10 Rebate is : 1
- 4 years ago
- Afaq Arif
- 2,837 Views
-
4