DEV Community

Cover image for OOPs Concepts in TypeScript. What is the 4, Basics of Object-Oriented Programming Fundamentals & their Examples
Reagan Scofield
Reagan Scofield

Posted on

OOPs Concepts in TypeScript. What is the 4, Basics of Object-Oriented Programming Fundamentals & their Examples

1. Abstraction

Abstraction lets programmers create useful and reusable tools. For example, a programmer can create several different types of objects, which can be variables, functions or data structures. Programmers can also create different classes of objects as ways to define the objects. For instance, a class of variable might be an address. The class might specify that each address object shall have a name, street, city and zip code. The objects, in this case, might be employee addresses, customer addresses or supplier addresses.

Abstraction Example:

abstract class Address {
    private street: string;
    private city: string;
    private codePostal: number;

    constructor(street: string, city: string, codePostal: number){
        this.street = street;
        this.city = city;
        this.codePostal = codePostal;
    }

    public getFullAddress(): string {
        return `${this.street}, ${this.city}, ${this.codePostal}`;
    }
}

class FirstCustomer extends Address {
    constructor(street: string, city: string, codePostal: number){
        super(street, city, codePostal);
        console.log(city)
    }
}

class SecondCustomer extends Address {
    constructor(street: string, city: string, codePostal: number){
        super(street, city, codePostal);
        console.log(city)
    }
}

new FirstCustomer("234 Washigton Road", "Honolulu", 283930);
new SecondCustomer("456 Mandela Street", "New Jarsey", 58893);
Enter fullscreen mode Exit fullscreen mode

2. Encapsulation

Encapsulation lets us reuse functionality without jeopardising security. It’s a powerful, time-saving OOP concept in TypeScript which related to Java. For example, we may create piece of code that calls specific data from a database. It may be useful to reuse that code with other databases or processes. Encapsulation lets us do that while keeping our original data private. It also lets us alter our original code without breaking it for others who have adopted it in the meantime.

Encapsulation Example:

class Customer {
    private name: string;
    private surname: string;

    public getFullName(): string {
      return `${this.name} - ${this.surname}`;
    }

    public setNames(name: string, surname: string): void {
      this.name = name;
      this.surname = surname;
    }
}

class SetGetCustomer {
    constructor(){
        const name: string = "Jon";
        const surname: string = "Snow";
        const customer: Customer = new Customer();
        customer.setNames(name, surname);
        const fullname: string = customer.getFullName();
    }
}

new SetGetCustomer();
Enter fullscreen mode Exit fullscreen mode

3. Inheritance

Inheritance is another labor-saving OOP concept that works by letting a new class adopt the properties of another. We call the inheriting class a subclass or a child class. The original class is often called the parent. We use the keyword extends to define a new class that inherits properties from an old class.

Inheritance Example

class ParentCustomer {
    private surname: string = "Scofield";
    public familyName(): string {
        return this.surname;
    }
}

class ChildCustomer extends ParentCustomer {
    private name: string;
    constructor(name: string){
        super();
        this.name = name;
    }
    public childFullName(): string {
        const surname: string = this.familyName();
        return `${this.name} - ${surname}`;
    }
}

new ChildCustomer("Aleah");
new ChildCustomer("Reagan");
Enter fullscreen mode Exit fullscreen mode

4. Polymorphism

Polymorphism in TypeScript works by using a reference to a parent class to affect an object in the child class. We might create a class called “horse” by extending the “animal” class. That class might also implement the “professional racing” class. The “horse” class is “polymorphic,” since it inherits attributes of both the “animal” and “professional racing” class. Two more examples of polymorphism in Java are method overriding and method overloading.

In method overriding, the child class can use the OOP polymorphism concept to override a method of its parent class. That allows a programmer to use one method in different ways depending on whether it’s invoked by an object of the parent class or an object of the child class.In method overloading, a single method may perform different functions depending on the context in which it’s called. This means a single method name might work in different ways depending on what arguments are passed to it

Polymorphism Example

class CustomerPolymorphism {
    canComplaining(): void {
        console.log("The Customer is wrong on this matter");
    }
}

class CustomerPolymorphismOverride extends CustomerPolymorphism {
    canComplaining(): void {
      console.log("Stop that, We y'all Customer is always right no matter what")
    }
    public main(): void {
      this.canComplaining();
    } 
}

const customerPolymorphismOverride: CustomerPolymorphismOverride = new CustomerPolymorphismOverride();
customerPolymorphismOverride.main();
Enter fullscreen mode Exit fullscreen mode

Let's us connect on linkedIn. profile name is: Reagan Scofield Mukandila

Discussion (5)

The discussion has been locked. New comments can't be added.
Collapse
lukeshiru profile image
Info Comment hidden by post author - thread only accessible via permalink
Luke Shiru • Edited on

Is a pretty common misconception to include inheritance and classes as part of OOP, but they aren't actually part of it.

The pioneer of OOP, Alan Kay, when talking about the meaning of OOP, said:

OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.

So the actual basic ingredients of OOP are:

  • Message passing.
  • Encapsulation.
  • Dynamic binding.

You might notice that "inheritance" and classes are not considered essential. Classes are just one way of doing encapsulation, but JavaScript (and by consequence TypeScript) has other ways of achieving encapsulation that are more flexible and composable than classes, namely functions, closures and modules.

Not only that, you also used the abstract keyword to give an example of the concept of "abstraction", when that concept has nothing to do with keywords. Is like saying that the definition of "math" is the + operator.

If you're wondering how your encapsulation would look like without class:

const createCustomer = () => {
    const customer: {
        name?: string;
        surname?: string;
    } = {};

    return {
        getFullName: () => `${customer.name} - ${customer.surname}`,
        setNames: (name: string, surname: string) => {
            customer.name = name;
            customer.surname = surname;
        },
    };
};

const customer = createCustomer();
customer.setNames("John", "Doe");
customer.getFullName(); // "John - Doe"
Enter fullscreen mode Exit fullscreen mode

Tho is worth mentioning that for something like this, is way better to make it more functional:

type FullName = {
    name: string;
    surname: string;
};

const fullNameToString = ({ name, surname }: FullName) => `${name} ${surname}`;

const updateFullName =
    (update: Partial<FullName>) =>
    <WithFullName extends FullName>(
        withFullName: WithFullName,
    ): WithFullName => ({
        ...withFullName,
        ...update,
    });

const customer = {
    name: "John",
    surname: "Doe",
} as const;

fullNameToString(customer); // "John Doe"
fullNameToString(updateFullName({ name: "Jane" })(customer)); // "Jane Doe"
Enter fullscreen mode Exit fullscreen mode

Now instead of having methods locked inside a Customer class, we have utils that we can reuse with anything that has FullName on it.

Cheers!

Collapse
lukeshiru profile image
Luke Shiru • Edited on

Why did you hid my comment @reaganscofield ? ... I wasn't being offensive or anything like that, I just added some clarity to your post :/

Collapse
dinniej profile image
Info Comment hidden by post author - thread only accessible via permalink
Nguyen Ngoc Dat

The first example is just inheritance. There is nothing abstraction about that

Collapse
donnyroufs profile image
Info Comment hidden by post author - thread only accessible via permalink
donny roufs

The first example is pretty much inheritance. An abstract class should force a dev to implement something but not all. Your example just inherits.

Collapse
davidbug profile image
Info Comment hidden by post author - thread only accessible via permalink
davidildefonso

Thanks Man Is good info

Some comments have been hidden by the post's author - find out more