Friday, August 10, 2018

Classes and objects in typescript | inheritance examples

In this tutorial, we are going to learn the classes in typescript programming language.classes and objects are the basic elements of object-oriented programming. Classes hold the data and represent the behavior or methods that operated on it.

Typescript Classes and Objects

Javascript has classes as the part ES6 version. Typescript also introduced classes and objects. The class is a prototype or blueprint for created objects.
The class is a list of objects of the same type. It means each object holds the different data and these data are used in methods to achieve class behavior.

Class Declaration example

The class can be created using keyword class It contains properties/variables, methods, and constructor.
Below is Typescript code for class declaration
class Employee {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    getName() {
        return name;
    }
}
Generated Javascript code is
var Employee = /** @class */ (function () {
    function Employee(name) {
        this.name = name;
    }
    Employee.prototype.getName = function () {
        return name;
    };
    return Employee;
}());
In the above example, Created Employee class. It has a name as property variable name and constructor is provided, and returned the name object using a getter.

Object Creation example

Each class can have multiple objects. Each object has specific properties which operated by methods Object can be created using a new operator which allocates space in the memory area
let emp1 = new Employee("Kiran");
let emp2 = new Employee("Kiran");
In the above example, Created two objects called emp1 and emp2. Each object property(in this case, name) is different from other objects. These properties are called instance members from here onwards

Class Constructor 

 The constructor is used for initializing the instance members during object creation. These are optional Employee object is created using the new operator. During object creation, First, one called code is constructor which initializes member variables.

Class Inheritance 

Inheritance is one of object-oriented concent which is used to reuse all the properties and methods of the superclass object. You can create an own class which can extend the superclass and can write own behavior. This allows developers to maintain the code reusability and maintainability. Typescript supports inheritance using extends keyword.
class Animal {

    constructor(public isVeg: boolean, public legsCount: number) {
    }
    eat() {
        console.log(`eat non veg: ${this.isVeg}`);
    }
}
class Lion extends Animal { 
    jump: boolean;
    constructor(public isVeg: boolean, public legsCount: number, jump: boolean) {
        super(isVeg, legsCount);
        this.jump = jump;
    }
    roars() {
        console.log('lion roars');
    }
    jumpIn() {
        console.log('lion jumps');
    }
}
    let lion = new Lion(true, 4,true);
    lion.roars();  //  lion roars
    lion.eat();  //eat non veg: true
Notes
The animal class is called either parent or super or base class Lion class is called either child or subclass or derived class
Defined parent class Animal and child Lion class which extends parent class. if constructor in the child class, the First call should be superclass constructor you can add your child class properties in it
Rules
1. if there is a constructor in a child class which extends parent class must call parent class constructor using super keyword. Otherwise, it throws compilation error constructors for derived classes must contain a 'super' call

Abstract classes 

Abstract classes are same as classes except it contains abstract methods abstract method are methods which have the only declaration without implementation. An implementation need to provided by the classes which extend this abstract classes Abstract classes features this class contains either abstract methods and method implementation These classes will not be created an an object using the new operator It is not compulsory to have abstract methods

Syntax and Example

abstract class Shape {
    abstract area(): void;
    getName(): string {
        return 'Shape';
    }
}
// Generated Javascript code
var Shape = /** @class */ (function () {
    function Shape() {
    }
    Shape.prototype.getName = function () {
        return 'Shape';
    };
    return Shape;
}());
modifier accessibility
 In typescript, There are different types of accessor types applied to instance members or variable or properties and methods. 4 types available - public, private, protected, Readonly
Public modifier if the the variable is declared without a a modifier, compiler treat as public by default, This can be applied to variable declaration or constructor parameters as public or for methods if required. public or default declared variables or methods can access this variable from inside or outside of a class private modifier
This can be applied to the same variables or arguments in the constructor These are private to the class. a variable or methods declared with private has following accessibility rules.

  1. Can be used in a class 
  2. Can not be used in derived classes
  3. Can not be accessible outside of a class
  4. The object of the class not accessible 

protected modifier 
this modifier has following accessible rules

  1. Accessible in a declared class 
  2. Accessible in derived classes
  3. The object of the class not accessible
Readonly modifier. 
Instance member variables can b applied read-only modifier. This variables only initializes either in the declaration or in constructor only.

Class Static properties

Typescript has support for a static keyword for properties of a class. In general, each object holds different properties of a class. What if you want to maintain the same properties for all objects of a class? the answer is a static declaration Static Example
class StaticDemo {
    static staticPropertiy = 0;
    normalProperty = 0;
    constructor() {
        StaticDemo.staticPropertiy++;
       this.normalProperty++;
    }
}
var s1 = new StaticDemo();
var s2 = new StaticDemo();
console.log(StaticDemo.staticPropertiy); // outputs 2
console.log( s1.normalProperty); // outputs 1
console.log(s1.normalProperty); // outputs 1
Please share or comment if you have any questions.


EmoticonEmoticon

Note: Only a member of this blog may post a comment.