Object Oriented Programming With The Typescript
Object Oriented Programming With The Typescript
● What is a object :
//constructor
constructor(engine:string) {
this.engine = engine
}
//function
disp():void {
console.log("Engine is : "+this.engine)
}
}
let customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
let employee:IPerson = {
firstName:"Jim",
lastName:"Blakes",
sayHi: ():string =>{return "Hello!!!"}
}
Object
● An object is an instance which contains set of key value pairs. The values can
be scalar values or functions or even array of other objects.
● The syntax is given below −
let object_name = {
var person = {
key1: “value1”, //scalar value
firstname:"Tom",
key2: “value”,
lastname:"Hanks"
key3: function() {
};
//functions
//access the object values
},
console.log(person.firstname)
key4:[“content1”, “content2”] //collection
console.log(person.lastname)
};
Encapsulation
● encapsulation enables you to perform what’s called “data hiding”.
● It’s necessary to hide certain data so that it’s not changed accidentally or
purposefully by other components or code in the program.
● To achieve encapsulation, use the proper access modifiers combined with the
proper member types to limit or expose the scope of data.
● Access modifiers are markers on code that designate where that code can be
used, and are as follows: public, private, and protected.
class BankAccount {
1. Public - By default, members (properties and methods) of the TypeScript class are public -
so you don’t need to prefix members with the public keyword. Public members are
accessible everywhere without restrictions even from the multiple level sub-classes without
any compile errors.
2. Private - A private member cannot be accessed outside of its containing class. Private
members can be accessed only within the class and even their sub-classes won't be
allowed to use their private properties and attributes.
class baseClassName {
}
// Base class
class Person {
Name: string;
constructor(name: string) {
this.Name = name;
}
}
// Deriving Teacher class
class Teacher extends Person {
Payment: number;
constructor(name: string, payment: number) {
super(name);
this.Payment = payment;
}
display(): void {
console.log("Teacher's Name: " + this.Name);
console.log("Teacher's Payment " + this.Payment);
}
}
// Create Object
● In inheritance child class can consume members of it’s parent class as if it is the
owner of those members (except private members of parent class).
● Parent class constructor must be accessible to the child class, otherwise inheritance
will not be possible.
(Note : every class has a constructor)
● What is a constructor?
It is a special method present under a class responsible for initializing the
variable of that class. In inheritance child class can access parent class’s members
but parent class can never access any member that is purely defined under child
class.
● We can initialize a parent class variable by using child class instance to make it as a reference so
that reference will be consuming the memory of child class instance.
● What is a reference?
A reference is a pointer (variable that holds memory address) to an instance which does not
have any memory allocation.
Example :
Parent p;
Child c = new Child();
p = c;
● Every class that is defined by us or pre-defined in the libraries of language has a default parent class
i.e. Object class of system namespace. The members of Object class(Equals, getHashCode,
GetType, ToString) are accessible from anywhere.
Types of an inheritance
● It is based on the number of parent classes a child class have or the number
of child classes a parent class have.
● In general, there are five types of inheritance :
1. Single
2. Multi-level
3. Hierarchical
4. Hybrid
5. Multiple
Single Inheritance
● In single inheritance, the properties and behaviour of the base class can be inherited into at most one
derived class.
● It used to add new functionality to the already implemented class.
Parent Class
Child Class
Multilevel Inheritance
● In multilevel inheritance, the derived class acts as the base class for another derived class.
● The newly created derived class acquires the properties and behavior of other base classes.
Parent Class
Child Class
Parent Class
Parent Class
Grandchild Class 1
Multiple Inheritance
Child Class 1
Polymorphism
● Polymorphism is the ability to create a class that has more than one form. Or
in other words, classes have the same methods but different implementations.
● There are two types of polymorphism
1. Compile time polymorphism.
2. Runtime polymorphism.
● Compile Time Polymorphism can be achieved using function overloading.
● Runtime polymorphism can be achieved using function overriding.
Function Overloading
● Function overloading is a mechanism or ability to create multiple methods
with the same name but different parameter types and return type. However, it
can have the same number of parameters.
● Function overloading is also known as method overloading.
● The Function/Method overloading is allowed when:
1. The function name is the same
2. The number of parameters is the same, and their type is different.
3. The all overloads function must have the different return type.
● Advantages -
1. Compiling a code is too fast since it saves memory space.
2. Maintaining a code is easy.
3. It provides code reusability, which saves time and effort.
4. Readability of the program increases.
Class First {
public folder(s: string): number;
public folder(n: number): string;
public folder(arg: any): any {
if (typeof(arg) === 'number')
return arg.toString();
if (typeof(arg) === 'string')
return arg.length;
}
}
let obj = new First();
console.log("Result: " + obj.folder(101));
console.log("Length of String: " + obj.folder("CodingNinjas"));
Function Overriding
● Method Overriding is the process in which a method belonging to the base (or
parent) class is overridden by the same method (same method and signature)
of the derived (child) class.
● In this process, a child (derived) class method may or may not use the logic
defined in the parent (base) class method.
● In order to invoke the methods or properties of the base class, we may use
the super keyword which would help us to invoke that particular method or
property of the base class into the child class.
● Method Overriding is useful whenever we want to alter the behavior of any
method of the parent class in child class.
class Animal {
public name: string;
class Cat extends Animal {
constructor(name: string) {
public makeSound(): void {
this.name = name;
console.log('meow meow\n');
}
}
}
public makeSound(): void {
console.log('generic animal sound\n');
const pocky: Cat = new Cat('Pocky');
}
pocky.makeSound(); // -> meow meow
}
const toshii: Dog = new Dog('Pocky');
class Dog extends Animal {
toshii.makeSound(); // -> wuff wuff
public makeSound(): void {
console.log('wuff wuff\n');
}
}
Class Boy {
}
class Student extends Boy {
rollnumber : number;
marks: number;
constructor(rollnumber : number, marks : number,
name1 : string){
super();
this.rollnumber = rollnumber
this.name = name1
this.marks = marks let student = new Student(2, 96, "Rohit");
} student.displayStudentInformation();
displayStudentInformation() : void { student.about();
console.log("Name : "+ this.name +", Roll
Number : " +
this.rollnumber +",
Scores : " + this.marks + " out of 100" )
}
about() : void {
// Invokes parent class about() method here also.
super.about();
console.log(this.name + " scores well...")
}
}
Abstraction
● Abstraction means hiding lower-level details and exposing only the essential
and relevant details to the users.
● The concept behind abstraction is that we are hiding the complexity of the
implementation from inherited classes and we allow them to implement the
functionality themselves.
● In TypeScript, abstraction can be achieved by using the abstract keyword -
which can be applied to both classes and methods specified in classes.
interface Fee {
chargeFee(amount: number );
}