0% found this document useful (0 votes)
285 views

Object Oriented Programming With The Typescript

1. Object Oriented Programming (OOP) deals with classes and objects. A class defines common properties and behaviors, while an object is an instance of a class. 2. The key pillars of OOP include classes, objects, interfaces, encapsulation, inheritance, polymorphism, and abstraction. Classes define properties and behaviors, objects are instances of classes, and interfaces define common structures without implementations. 3. Inheritance allows classes to extend existing classes, reusing their properties and behaviors. Polymorphism enables classes to have different implementations of the same methods. Encapsulation hides implementation details and controls access to properties and methods.

Uploaded by

Revati Katekhaye
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
285 views

Object Oriented Programming With The Typescript

1. Object Oriented Programming (OOP) deals with classes and objects. A class defines common properties and behaviors, while an object is an instance of a class. 2. The key pillars of OOP include classes, objects, interfaces, encapsulation, inheritance, polymorphism, and abstraction. Classes define properties and behaviors, objects are instances of classes, and interfaces define common structures without implementations. 3. Inheritance allows classes to extend existing classes, reusing their properties and behaviors. Polymorphism enables classes to have different implementations of the same methods. Encapsulation hides implementation details and controls access to properties and methods.

Uploaded by

Revati Katekhaye
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Object Oriented Programming

with the Typescript


- Mukund Thakare
What is object oriented programming ?
● OOP is all about dealing with the classes and its objects.
● What is a class ?
A class is a collection of various members like fields, methods,
constructor etc.

Example : Mobile phone.

● What is a object :

Object is an real life entity of the class. It is also called as an instance.


class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
Pillars of Object Oriented Programming
● Class
● Object
● Interface
● Encapsulation
● Inheritance
● Polymorphism
● Abstraction
Class
● A class in terms of OOP is a blueprint for creating objects. A class
encapsulates data for the object.
● The class keyword is followed by the class name. The rules for identifiers
must be considered while naming a class.
● A class definition can include the following −
○ Fields − A field is any variable declared in a class. Fields represent data pertaining to objects
○ Constructors − Responsible for allocating memory for the objects of the class
○ Functions − Functions represent actions an object can take. They are also at times referred
to as methods
● These components put together are termed as the data members of the class.
class Car {
//field
engine:string;

//constructor
constructor(engine:string) {
this.engine = engine
}

//function
disp():void {
console.log("Engine is : "+this.engine)
}
}

var obj = new Car("Engine 1")


Interface
● Interfaces define properties, methods, and events, which are the members of
the interface.
● Interfaces contain only the declaration of the members.
● It is the responsibility of the deriving class to define the members.
● It often helps in providing a standard structure that the deriving classes would
follow.
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}

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 {

public minimumBalance: number;


private _balance: number;

get balance(): number {


return this._balance;
}

deposit(amount: number): number {


this._balance = this._balance + amount;
return this._balance;
}

withdraw(amount: number): number {


if (amount <= this.minimumBalance) {
this._balance = this._balance - amount;
return this._balance;
}
}
}
Access Modifiers
● TypeScript supports three access modifiers - public, private, and protected.

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.

3. Protected - A protected member cannot be accessed outside of its containing class.


Protected members can be accessed only within the class and by the instance of its
sub/child class.
Inheritance
● What is Inheritance?
It is a mechanism of consuming the members of one class in another class by
establishing parent-child relationship between the classes which provides the
re-usability.
● What is need of inheritance?
To avoid repetition of code.
We can simply define class(parent) and use it’s members in multiple classes(child
classes) using inheritance.
Syntax:

class baseClassName {

class derivedClassName extends 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

let obj = new Teacher("GeeksforGeeks", 8500000);


obj.display();
Properties of Inheritance

● 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

Grand Child Class


// Base class
class Vehicle {
Type(): void {
// Inherited all properties of
console.log("Car");
// Vehicle and Car class
}
class carModel extends Car {
}
Model(): void {
console.log("ABC2021");
// Inherited from Vehicle
}
class Car extends Vehicle {
}
Brand(): void {
console.log("ABC");
}
}
Hierarchical Inheritance

Parent Class

Child Class 1 Child Class 2


Hybrid Inheritance

Parent Class

Child Class 1 Child Class 2

Grandchild Class 1
Multiple Inheritance

Parent Class 1 Parent Class 2

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 );
}

// parent BankAccount and sibling SavingsAccount do not implement Fee interface


class BankAccount { ... }
class SavingsAccount extends BankAccount { ... }

// checking implements Fee


class CheckingAccount extends BankAccount implements Fee {
chargeFee(amount: number) {}
}

// BusinessChecking inherits CheckingAccount and therefore Fee


class BusinessChecking extends CheckingAccount { … }

// Code that uses BusinessChecking can call chargeFee


function CalculateMonthlyStatements() {
let businessChecking = new BusinessChecking();
businessChecking.chargeFee(100);
}
Thank you !!

You might also like