This content originally appeared on Level Up Coding - Medium and was authored by Hayk Simonyan
Intro
In this article, we’ll look at the core OOP concepts with real code examples, which will make it easier for you to understand the fundamentals.
Before we dive into the concepts of OOP, let’s clarify the difference between a class and an object.
Class vs Object
A class is like a blueprint, while an object is an instance of that blueprint.
Think of a class as a blueprint of a house, and an object as an actual house.
To illustrate this point, let’s look at this example
class Person {
name: string;
age: number;
}
const person1 = new Person();
person1.name = "John";
person1.age = 30;
const person2 = new Person();
person2.name = "Jane";
person2.age = 25;
In this example, the Person class is a blueprint that defines the properties of a person. We create two objects, person1 and person2, which are instances of the Person class. Each object has its own values for the name and age properties.
Introduction to OOP
Now, let’s define what OOP is. OOP is a programming paradigm that uses the concept of objects and classes to represent data and behaviors. It makes code more organized, reusable, and easier to maintain.
OOP Concepts
OOP has 4 core concepts:
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
Encapsulation
Encapsulation is the process of hiding data and behavior within a class, making it inaccessible to other classes or code.
Think of a black box where you can only interact with the inputs and outputs, while the internal workings remain hidden.
Here’s an example:
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
public deposit(amount: number): void {
this.balance += amount;
}
public withdraw(amount: number): void {
if (this.balance >= amount) {
this.balance -= amount;
} else {
console.log("Insufficient balance");
}
}
public getBalance(): number {
return this.balance;
}
}
In this example, the BankAccount class has a private property balance, which is only accessible within the class. The public methods deposit, withdraw, and getBalance provide a way to interact with the balance property, while keeping it hidden from other classes or code.
If you try to retrieve the balance bankAccount.balance you will get an error because it is inaccessible from the outside world.
Abstraction
Abstraction is the process of simplifying complex systems by breaking them down into smaller, more manageable parts.
Think of a car where the driver only needs to know how to use the steering wheel, pedals, and gears, without knowing how the engine works.
Here’s an example:
abstract class Animal {
abstract makeSound(): void;
}
class Dog extends Animal {
makeSound(): void {
console.log("Woof");
}
}
class Cat extends Animal {
makeSound(): void {
console.log("Meow");
}
}
In this example, the Animal class is an abstract class that defines an abstract method makeSound. The Dog and Cat classes extend the Animal class and provide their own implementation of the makeSound method. This allows us to create objects of type Dog or Cat without having to know the details of how they make their sound.
This means that a user only needs to know the high-level functionality of a system without knowing the internal details.
Inheritance
Inheritance is the mechanism that allows a class to inherit properties and behaviors from a parent class.
Think of a family tree where a child inherits some characteristics from their parent.
To explain Inheritance, let’s consider an example where we have a parent class called Animal and two child classes called Dog and Cat. Both the Dog and Cat classes inherit the properties and methods of the Animal class, which means they can access and use the same properties and methods as the Animal class.
class Animal {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
eat() {
console.log(`${this.name} is eating.`);
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, age: number, breed: string) {
super(name, age);
this.breed = breed;
}
bark() {
console.log(`${this.name} is barking.`);
}
}
class Cat extends Animal {
breed: string;
constructor(name: string, age: number, breed: string) {
super(name, age);
this.breed = breed;
}
sleep() {
console.log(`${this.name} is sleeping.`);
}
}
const dog = new Dog("Daisy", 1, "Bulldog");
const cat = new Cat("Whiskers", 2, "Birman");
dog.eat(); // Output: "Daisy is eating."
dog.bark(); // Output: "Daisy is barking."
cat.eat(); // Output: "Fluffy is eating."
cat.sleep(); // Output: "Fluffy is sleeping."
The Dog class has an additional property called breed and a method called bark, while the Cat class has an additional property called breed and a method called sleep.
This means that a subclass can reuse code from its parent class, which allows us to reuse code and avoid duplicating common functionality across classes.
Polymorphism
The fourth concept of OOP is Polymorphism which is the ability of an object to behave differently based on the context in which it is used.
For example, a person can be a teacher in one context and a student in another.
In programming, this means that we can create multiple classes that inherit from a common parent class and have their own unique implementations of the parent’s methods.
For example, let’s say we have an interface Shape which defines a method calculateArea().
interface Shape {
calculateArea(): number;
}
class Rectangle implements Shape {
private width: number;
private height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
calculateArea(): number {
return this.width * this.height;
}
}
class Circle implements Shape {
private radius: number;
constructor(radius: number) {
this.radius = radius;
}
calculateArea(): number {
return Math.PI * Math.pow(this.radius, 2);
}
}
function printArea(shape: Shape): void {
console.log(`The area is ${shape.calculateArea()}`);
}
const rectangle = new Rectangle(10, 20);
const circle = new Circle(5);
printArea(rectangle); // Output: The area is 200
printArea(circle); // Output: The area is 78.53981633974483
We then have two classes, Rectangle and Circle, which both implement the Shape interface and provide their own implementation of the calculateArea() method.
Finally, we have a printArea() function which takes an argument of type Shape and calls its calculateArea() method to print the area of the shape.
By using the Shape interface and implementing it in both the Rectangle and Circle classes, we can treat both shapes as Shape objects in the printArea() function.
Summary
In Summary, OOP is a programming paradigm that uses the concept of objects and classes to represent data and behaviors and it has 4 core concepts:
- Encapsulation is the process of hiding implementation details while providing a public interface.
- Abstraction is the process of hiding complex implementation details while providing a simple interface.
- Inheritance allows new classes to be based on existing classes and to inherit properties and methods from their parent class
- Polymorphism allows objects of different types to be treated as if they were the same type.
Before you go: If you found this helpful — 👏 Clap for the story and follow me for more 🔔
Level Up Coding
Thanks for being a part of our community! Before you go:
- 👏 Clap for the story and follow the author 👉
- 📰 View more content in the Level Up Coding publication
- 💰 Free coding interview course ⇒ View Course
- 🔔 Follow us: Twitter | LinkedIn | Newsletter
🚀👉 Join the Level Up talent collective and find an amazing job
OOP Concepts Simplified was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Hayk Simonyan
Hayk Simonyan | Sciencx (2023-04-06T02:40:12+00:00) OOP Concepts Simplified. Retrieved from https://www.scien.cx/2023/04/06/oop-concepts-simplified/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.