Skip to content

Commit

Permalink
Learned about OOP classes and Objects, Encapsulation and Abstraction …
Browse files Browse the repository at this point in the history
…concepts
  • Loading branch information
sohail019 committed Jul 27, 2024
1 parent 94a9e57 commit 6d9264b
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Class declaration
class Person{ // class ka naam Person hai

// constructor method se object initialize hoga
constructor(name, age){
this.name = name
this.age = age
}

// Method ye greet method object ke behaviour ko define karega
greet(){
console.log(`Hello my name is ${this.name} and I am ${this.age} years old`);
}
}

// Creating an object from the class
const person1 = new Person('Sohail', 21)
person1.greet() // Output: Hello my name is Sohail and I am 21 years old.

// Another object
const person2 = new Person('Jamil', 20)
person2.greet()
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Encapsulation

class BankAccount{

// #balance ek private field hai jo directly class ke bahar se accessible nahi hai.
#balance

constructor(initialBalance){
this.#balance = initialBalance // initialize private field
}

// Public Methods: deposit, withdraw, aur getBalance public methods hain jo object ke internal state ko access aur modify karne ki permission dete hain.

// Public method banate hai money deposit karne ke liye
deposit(amount){
if(amount > 0){
this.#balance += amount
}
}

// Public method banate hai money withdraw karne ke liye
withdraw(amount){
if (amount > 0 && amount <= this.#balance) {
this.#balance -= amount
}
}

// Public method banate hai balance dekhne ke liye
getBalance(){
return `Balance is ${this.#balance}`
}
}

const account1 = new BankAccount(1000);
account1.deposit(1000) // 1000 deposit hua to balance hua 2000
console.log(account1.getBalance()) // 2000

account1.withdraw(1200) // 1200 withdraw karne pe 800 balance hona chahiye
console.log(account1.getBalance())
// Upar ka methods ke through private property access horahi hai par agar private property ko direct access karne ki koshish karenge to dekhte hai kya hota hai

// console.log(account1.#balance) // // SyntaxError: Private field '#balance' must be declared in an enclosing class
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Abstraction
class Car{
constructor(make, model){
this.make = make
this.model = model
}


// Abstracted Method
startEngine(){
console.log("Engine started");
}

// Abstracted Method
drive(){
console.log("Car is Driving.");
}
}

const myCar = new Car("Toyota", "Fortuner")

myCar.startEngine()
myCar.drive()

0 comments on commit 6d9264b

Please sign in to comment.