Object -based programming (OOP) is one of the most used programming samples in software development. But this is one of the most misunderstood.
This article will help you get the solid grip of OOP in the type script that you walk through the features of the language that supports it, and then show how these features naturally give rise to the four basic principles: InheritanceFor, for, for,. PolymorphismFor, for, for,. EncapsulationAnd Abstract.
Provisions
You should be aware of this article, you should be familiar with:
The basic principles of JavaScript – Variable, functions, items and rows.
Basic type script syntax – including the types and how they are different from the simple Javascript.
The table of content
How to read this article
I have organized this article in two parts. The first section covers the type script language features that enable you to implement the Object -based programming (OOP). The second section discusses the concepts derived from the characteristics that lead to four OOP principles: inheritance, polymorphism, incubation and abstraction.
Although many teachers, books and courses begin to explain these principles, I prefer to start with the features of the language myself. The reason is easy: they are formal structures – in other words, concrete. In addition, throughout the article, you will see that the OOP principles emerge when you use the language structure properly.
Features of type script language
In this section, we will find the features of the type script that facilitate the implementation of the OOP. Similar mechanisms are present in other objects -based languages, such as Java and C#, though they can vary in syntax while preserving basic concepts.
Object
One item is a data type that saves a combination of organized values in a key/value pairs. These may include ancient data or other items.
In the following example, person
The object stores different pieces of information, such as key name
In which value is "Lucas"
Type string
And address
The key, which is one more thing.
const person = {
name: "Lucas",
surname: "Garcez",
age: 28,
address: {
city: "Melbourne",
country: "Australia",
},
};
Class, attributes and ways
A blueprint works to make a class items. It explains the structure and behavior of an item through its attributes and methods. Excellence outlines the structure of the data (types of keys and value), while methods explain the actions that can be performed on these attributes.
class Person {
name: string;
surname: string;
age: number;
constructor(name: string, surname: string, age: number) {
this.name = name;
this.surname = surname;
this.age = age;
}
getFullName() {
return `${this.name} ${this.surname}`;
}
}
The method of the builder
Construction is a special way within the class. When a new item is ready, it is automatically demanded. Construction is responsible for starting class attributes with the values provided during the object of the object. In the type script, described using the conductor constructor
The key word, as you can see in the code mentioned.
Example
An example refers to the item born from a class. For example, to use the class Person
The above mentioned above, you can create an item called name name lucas
. Hence, lucas
Is an instance of the class Person
. JavaScript or type script to create an example of an item you, you use the key word new
As shown below:
const lucas = new Person("Lucas", "Garcez", 28);
lucas.name;
lucas.getFullName();
It is important to note that you can create multiple items from the same class. Although all of these items share the same structure (attributes and methods), they are free and occupy separate memory locations within the program.
For example, when making a new item:
const maria = new Person("Maria", "Oliveira", 19);
Now you have a new example Person
Class that does not interfere with the creation of the previous lucas
The object every example maintains its values and behaviors, ensuring that manipulation in an item does not affect others.
Interface
An interface describes an agreement that is established, whose characteristics and methods should be implemented in the class. In the type script, this relationship has been set up using keywords implements
. When a class enforces an interface, it will have to include all attributes and methods described by this interface and their related types.
In the following example, you have a banking system where a user may have even CurrentAccount
Or SavingsAccount
The account must follow the rules of the bank’s general account of both options that BankAccount
Interface
interface BankAccount {
balance: number;
deposit(amount: number): void;
withdraw(amount: number): void;
}
class CurrentAccount implements BankAccount {
balance: number;
overdraftLimit: number;
deposit(amount: number): void {
this.balance += amount;
}
withdraw(amount: number): void {
if (amount <= this.balance) {
this.balance -= amount;
}
}
}
class SavingsAccount implements BankAccount {
balance: number;
deposit(amount: number): void {
}
withdraw(amount: number): void {
}
}
Summary classes
Like the interface, abstract classes explain a model or contract on which other classes should also be followed. But although an interface only describes the structure of a class without implementing the structure, an abstract class may include procedure declarations and solid implementation.
Unlike regular classes, though, abstract classes Could not directly be done – They are completely present as a base from where other classes can inherit their methods and attributes.
In the type script, abstract
Keywords are used to explain an abstract class. In the following example, you will reflect the interface with an abstract class instead of the interface to explain the base behavior for all bank accounts.
abstract class BankAccount {
balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number): void {
this.balance += amount;
}
abstract withdraw(amount: number): void;
}
class CurrentAccount extends BankAccount {
withdraw(amount: number): void {
const fee = 2;
const totalAmount = amount + fee;
if (this.balance >= totalAmount) {
this.balance -= totalAmount;
} else {
console.log("Insufficient balance.");
}
}
}
class SavingsAccount extends BankAccount {
withdraw(amount: number): void {
if (this.balance >= amount) {
this.balance -= amount;
} else {
console.log("Insufficient balance.");
}
}
}
const genericAccount = new BankAccount(1000);
const currentAccount = new CurrentAccount(2000);
currentAccount.deposit(500);
currentAccount.withdraw(300);
const savingsAccount = new SavingsAccount(1500);
savingsAccount.deposit(1100);
savingsAccount.withdraw(500);
The principle of object -based programming
Now that you understand the important language method, you can formulate objects of object -based programming that guide the creation of systems that are better organized, reused and expanded.
Heritage – super class and subclasses
Inheritance is a method that allows the class to gain features from another class. When a class B
Is inherited from a class A
It means B
Automatically acquires attributes and methods A
Need to explain them.
You can see this relationship as a parent child’s structure, where A
Super class (twenty/parent class) and is B
Subclass (derived/children’s class). A sub -class can use the inherited resources, add new behavior, or override super -class methods to solve specific needs.
We have already discussed the inheritance when learning about summary classes, but the inheritance can also be applied to concrete classes. This allows the code to reuse and use the skills.
class BankAccount {
balance: number = 0;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number): void {
this.balance += amount;
}
withdraw(amount: number): void {
if (amount <= this.balance) {
this.balance -= amount;
}
}
}
class CurrentAccount extends BankAccount {
overdraftLimit: number;
constructor(initialBalance: number, overdraftLimit: number) {
super(initialBalance);
this.overdraftLimit = overdraftLimit;
}
override withdraw(amount: number): void {
const totalAvailable = this.balance + this.overdraftLimit;
if (amount > 0 && amount <= totalAvailable) {
this.balance -= amount;
}
}
}
const currentAccount = new CurrentAccount(0, 100);
currentAccount.deposit(200);
currentAccount.withdraw(250);
Polymorphism
Polymorphism is a concept that often confuses object -based programming. But in practice, this is merely a natural consequence of the interface and inheritance use.
The term polymorphism begins in Greek and it means “many forms” (poly = many, morphos = form). This concept allows items coming from different classes to respond to the same way call, but with separate implementation, the code makes the code more flexible and reusable.
To clarify this concept, let’s consider a practical example. Suppose your name is the name sendMoney
Responsible for action on financial transactions, transferring a certain amount from Account A to Account B. The only requirement is that both accounts follow the joint contract, ensuring ways. withdraw
And deposit
Available.
function sendMoney(
sender: BankAccount,
receiver: BankAccount,
amount: number
) {
sender.withdraw(amount);
receiver.deposit(amount);
}
const lucasAccount = new CurrentAccount(500, 200);
const mariaAccount = new SavingsAccount(300);
sendMoney(lucasAccount, mariaAccount, 100);
Polymorphic methods:
withdraw
And deposit
Called within the methods sendMoney
Function without a function to find out whether it is dealing with one CurrentAccount
Or SavingsAccount
. Each class applies withdraw
According to its own rules, showing the concept of polymorphism.
Decoupling:
sendMoney
The function does not depend on a specific type of bank account. Any class that extends BankAccount
(If it is class) or applied BankAccount
(If this is an interface) can be used without a modification requirement sendMoney
Ceremony
With this approach, you ensure flexibility and code maintenance, as new types of account can be introduced without affecting functionality sendMoney
.
Encapsulation
Incapulation is one of the basic principles of OOP, but it can be applied to any programming model. This includes hiding the module, class, function, or hiding the internal execution details of any other software component, only exposing something necessary for external use. This improves code security, maintaining and modification by preventing unauthorized access and ensuring controlled interaction.
Access to edit – public
For, for, for,. private
And protected
In the OOP, an inquiry is essential to control the methods and attributes within the class. In the type script, it is obtained using access models, which are described by keywords public
For, for, for,. protected
And private
.
public
– Allows access to attributes or procedures inside and outside the class. This is a default default, which means that if no access to the editors in the code is defined, the type script assumes thatpublic
.protected
– Allows access within the class and its subclasses but prevents external access.private
– Limits access to attributes or methods within class only.
export class Person {
private firstName: string;
private lastName: string;
protected birthDate: Date;
constructor(firstName: string, lastName: string, birthDate: Date) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
}
public getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
class Professor extends Person {
constructor(firstName: string, lastName: string, birthDate: Date) {
super(firstName, lastName, birthDate);
}
getProfile() {
this.birthDate;
this.getFullName();
this.firstName;
this.lastName;
}
}
function main() {
const lucas = new Professor("Lucas", "Garcez", new Date("1996-02-06"));
lucas.birthDate;
lucas.getFullName();
lucas.firstName;
lucas.lastName;
}
The table of the editors in access
Modifier | Access to class | Access to Subclass | Access out of class |
public | ✅ YES | ✅ YES | ✅ YES |
protected | ✅ YES | ✅ YES | ❌ No |
private | ✅ YES | ❌ No | ❌ No |
Abstract
The concept of abstraction often causes confusion because it means technical context. If you look at the definition of this word in English, Cambridge describes the dictionary “Summary” As:
Anything that exists as an idea, feeling or standard rather than a material item.
This definition can be applied directly to the OOP: The summary represents an idea or concept without going into the details of concrete implementation.
Many online references as described as abuse “Hiding the details of the implementation“” Which can be misleading because this concept is closely related to the investigation. In OOP, abstract does not mean hiding details but also describe the contracts through summary Class And Interface.
interface BankAccountInterface {
balance: number;
deposit(amount: number): void;
withdraw(amount: number): void;
}
abstract class BankAccountClass {
balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number): void {
this.balance += amount;
}
abstract withdraw(amount: number): void;
}
In the above examples, both BankAccountInterface
And BankAccountClass
There are examples of summary as they explain the contracts that should be implemented by users.
Conclusion
Although it is not easy to learn object -based programming, I hope this article has helped clarify the basic principles of OOP and modern titles.
If you want to learn type scripts and OOPs, I recommend reading Martin Fuler’s book a lot Refecting: Improve the current code design. This book contains a large scale of retacting techniques, and the second edition contains examples of all code written in the type script, many of which are used here.