0% found this document useful (0 votes)
9 views40 pages

Introduction to OOP in Each Language-

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

Introduction to OOP in Each Language-

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Introduction to OOP in Each Language:

You should explain whether each language follows a class-based or prototype-based


approach to OOP.
• C++ → Class-based
• Python → Class-based
• Java → Class-based
• PHP → Class-based
• JavaScript → Prototype-based (but also supports class-based OOP with
ES6)

Classes and objects


In c++:
To create a class, use the class keyword:

To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Create an object called "myObj" and access the attributes:
In java:
In Java, you define a class using the class keyword. The class serves as a blueprint for
creating objects, defining their attributes (variables) and behaviors (methods).
Example:

Here, we created a class called Flower, with attributes name and color and a method
called pollination. This is pretty similar in C++.
Objects in java:
In Java, an object is created from a class. We have already created the class named Main, so
now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:
In PHP:
In PHP, a class is defined using the class keyword, followed by its name and a pair of
curly braces {}. Properties and methods are defined inside the class.
Objects of PHP:
Objects of a class are created using the newkeyword.
In the example below, $apple and $banana are instances of the class Fruit:
In java script:
Use the keyword class to create a class.
Always add a method named constructor():
Example

The example above creates a class named "Car".


The class has two initial properties: "name" and "year".
A JavaScript class is not an object.
It is a template for JavaScript objects.

When you have a class, you can use the class to create objects:

In python:
Python is an object oriented programming language.
To create a class, use the keyword class:
Constructor:
A constructor is a special method used to initialize objects when they are created. It is
automatically called when an object is instantiated.
In c++:

A constructor in C++ is a special method that is automatically called when an object of a


class is created.
To create a constructor, use the same name as the class, followed by parentheses ():
Constructor in PHP (__construct())
In PHP, the constructor is defined using the __construct() method.
Constructor in Java (ClassName())
In Java, the constructor has the same name as the class and is called when an object is
created.
class Fruit {
String name;
String color;

// Constructor
Fruit(String name, String color) {
this.name = name;
this.color = color;
}
void display() {
System.out.println("Fruit: " + name + ", Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects
Fruit apple = new Fruit("Apple", "Red");
Fruit banana = new Fruit("Banana", "Yellow");
apple.display();
banana.display();
}
}

Constructor in JavaScript (constructor())


In JavaScript (ES6+), the constructor is defined using the constructor() method inside a
class.
Example:

class Fruit {
constructor(name, color) {
this.name = name;
this.color = color;
}
display() {
console.log(`Fruit: ${this.name}, Color: ${this.color}`);
}
// Creating objects
const apple = new Fruit("Apple", "Red");
const banana = new Fruit("Banana", "Yellow");
apple.display();
banana.display();

Constructor in Python (__init__())

In Python, the constructor is defined using the __init__() method.

class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color

def display(self):
print(f"Fruit: {self.name}, Color: {self.color}")

# Creating objects
apple = Fruit("Apple", "Red")
banana = Fruit("Banana", "Yellow")

apple.display()
banana.display()
Inheritance:
Inheritance is an OOP principle where a new class (called the child class or derived
class) acquires the properties and behaviors (attributes and methods) of an existing
class (called the parent class or base class).

In c++
In C++, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
● derived class (child) - the class that inherits from another class
● base class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
In the example below, the Car class (child) inherits the attributes and methods from the
Vehicle class (parent):
Inheritance in PHP (extends)
PHP uses the extends keyword to create a child class that inherits from a parent class.
Inheritance in Java (extends)
Java also uses the extends keyword for inheritance.

Java Inheritance (Subclass and Superclass)


In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
● subclass (child) - the class that inherits from another class
● superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits the attributes and methods from the
Vehicle class (superclass):

class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Inheritance in JavaScript (extends & super()):
JavaScript uses extends to create a subclass and super() to call the parent constructor.

Create a class named "Model" which will inherit the methods from the "Car" class:
The super() method refers to the parent class.
By calling the super() method in the constructor method, we call the parent's constructor
method and gets access to the parent's properties and methods.

Inheritance in Python (super())


Python uses parentheses to inherit a class and super() to call the parent constructor.

# Parent class
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
print(f"{self.name} makes a sound.")

# Child class
class Dog(Animal):
def __init__(self, name):
super().__init__(name) # Call parent constructor

def bark(self):
print(f"{self.name} barks.")

# Creating an object
dog = Dog("Buddy")
dog.make_sound() # Inherited method
dog.bark() # Child class method
Polymorphism:
Polymorphism allows a method in different classes to have the same name but different
behavior. It enables method overriding and method overloading (in some languages).
In c++:
Uses keywords like virtual, override
#include <iostream>
using namespace std;
class Animal {
public:
virtual void makeSound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Dog barks" << endl;
}
};
int main() {
Animal* a;
Dog d;
a = &d;
a->makeSound();
return 0;
}

In PHP:

PHP supports method overriding, where a child class redefines a parent class method.
Example:
<?php
// Parent class
class Animal {
public function makeSound() {
echo "Some generic animal sound\n";
}
}
// Child class
class Dog extends Animal {
public function makeSound() { // Overriding method
echo "Dog barks\n";
}
}
// Creating objects
$animal = new Animal();
$dog = new Dog();

$animal->makeSound(); // Calls parent method


$dog->makeSound(); // Calls overridden method
?>

Polymorphism in Java (Method Overriding)


Java supports method overriding and method overloading.
Method Overriding Example:
// Parent class
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}
// Child class
class Dog extends Animal {
@Override
void makeSound() { // Overriding method
System.out.println("Dog barks");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Animal dog = new Dog(); // Polymorphism
animal.makeSound(); // Calls parent method
dog.makeSound(); // Calls overridden method
}
}
• The overridden method in Dog is called when using Animal dog = new
Dog();
• The @Override annotation ensures the method is correctly overridden.
Method Overloading Example:

class MathUtils {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}
public class Main {
public static void main(String[] args) {
MathUtils math = new MathUtils();
System.out.println(math.add(5, 10)); // Calls int version
System.out.println(math.add(5.5, 10.5)); // Calls double version
}
}
Polymorphism in JavaScript (Method Overriding)
JavaScript supports method overriding but does not have built-in method overloading.

// Parent class
class Animal {
makeSound() {
console.log("Some generic animal sound");
}
}
// Child class
class Dog extends Animal {
makeSound() { // Overriding method
console.log("Dog barks");
}
}
// Creating objects
let animal = new Animal();
let dog = new Dog();

animal.makeSound(); // Calls parent method


dog.makeSound(); // Calls overridden method

JavaScript supports overriding but not overloading (no method signatures like Java).
Simulating Overloading (Using Default Values)

class MathUtils {
add(a, b = 0) {
return a + b;
}
}
const math = new MathUtils();
console.log(math.add(5)); // 5 (b defaults to 0)
console.log(math.add(5, 10)); // 15

Polymorphism in Python (Method Overriding & Overloading)


Python supports method overriding and simulated overloading.
Method Overriding Example:

# Parent class
class Animal:
def make_sound(self):
print("Some generic animal sound")

# Child class
class Dog(Animal):
def make_sound(self): # Overriding method
print("Dog barks")

# Creating objects
animal = Animal()
dog = Dog()

animal.make_sound() # Calls parent method


dog.make_sound() # Calls overridden method
• The method make_sound() behaves differently in Animal and Dog.

Simulating Method Overloading (Using Default Arguments)


class MathUtils:
def add(self, a, b=0): # Simulating overloading
return a + b
math = MathUtils()
print(math.add(5)) # 5 (b defaults to 0)
print(math.add(5, 10)) # 15

• Python does not support method overloading natively, but we can use
default arguments
Abstraction
Abstraction is an OOP principle that hides implementation details from the user and
only exposes essential functionalities.
• Achieved using abstract classes or interfaces
• Forces child classes to implement specific methods
In c++:
virtual → Used to define abstract (pure virtual) functions.
• = 0 → Used to declare a pure virtual function, making the class abstract
Example:

#include <iostream>
using namespace std;

class Animal {
public:
virtual void makeSound() = 0; // Pure virtual function
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Dog barks" << endl;
}
};
int main() {
Dog d;
d.makeSound();
return 0;
}

Abstraction in PHP (abstract classes & methods)


PHP uses the abstract keyword to define abstract classes and methods.
• An abstract class cannot be instantiated.
• Child classes must implement all abstract methods.

<?php
// Abstract class
abstract class Animal {
public $name;

public function __construct($name) {


$this->name = $name;
}

abstract public function makeSound(); // Abstract method


}
// Child class
class Dog extends Animal {
public function makeSound() {
echo "$this->name barks\n";
}
}
// $animal = new Animal(); // Error: Cannot instantiate abstract class
$dog = new Dog("Buddy");
$dog->makeSound();
?>
Animal is abstract and cannot be instantiated.
• Dog must implement the makeSound() method.

Abstraction in Java (abstract classes & methods)


Java also uses the abstract keyword for abstraction.
Example:
// Abstract class
abstract class Animal {
String name;
Animal(String name) {
this.name = name;
}
abstract void makeSound(); // Abstract method
}
// Child class
class Dog extends Animal {
Dog(String name) {
super(name); }
@Override
void makeSound() {
System.out.println(name + " barks");
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Animal animal = new Animal("Generic"); // Error: Cannot instantiate abstract class
Dog dog = new Dog("Buddy");
dog.makeSound();
}
}
The Animal class is abstract, and Dog must implement makeSound().

Abstraction in JavaScript (Abstract behavior via classes & interfaces)


JavaScript does not have built-in abstract classes but can simulate abstraction using
ES6 classes.

// Simulating an abstract class


class Animal {
constructor(name) {
if (new.target === Animal) {
throw new Error("Cannot instantiate an abstract class");
}
this.name = name;
}
makeSound() {
throw new Error("Abstract method must be implemented");
}
}
// Child class
class Dog extends Animal {
makeSound() {
console.log(`${this.name} barks`);
}
}
// let animal = new Animal("Generic"); // Error
let dog = new Dog("Buddy");
dog.makeSound();
• Animal cannot be instantiated directly.
• Dog must implement makeSound() or it will throw an error.

Abstraction in Python (ABC module)


Python supports abstraction using the ABC module (Abstract Base Class).
Example:

from abc import ABC, abstractmethod

# Abstract class
class Animal(ABC):
def __init__(self, name):
self.name = name

@abstractmethod
def make_sound(self):
pass # Abstract method

# Child class
class Dog(Animal):
def make_sound(self):
print(f"{self.name} barks")
# animal = Animal("Generic") # Error: Cannot instantiate abstract class
dog = Dog("Buddy")
dog.make_sound()
Animal is abstract and cannot be instantiated.
• Dog must override make_sound().

Multiple Inheritance
Multiple inheritance allows a class to inherit from more than one class.
• Supported: Python, c++
• Not supported directly: PHP, Java, JavaScript (but can be simulated
using interfaces or mixins)
In c++
Keyword class, : (colon for multiple inheritance)
Example
#include <iostream>
using namespace std;
class Engine {
public:
void start() {
cout << "Engine started" << endl;
}};
class Wheels {
public:
void rotate() {
cout << "Wheels rotating" << endl;
}};
class Car : public Engine, public Wheels {
public:
void drive() {
cout << "Car is driving" << endl;
}
};
int main() {
Car myCar;
myCar.start();
myCar.rotate();
myCar.drive();
return 0;}

Multiple Inheritance in Python (Supported)


Python allows a class to inherit from multiple classes.

class Animal:
def speak(self):
return "Some sound"

class Dog:
def bark(self):
return "Woof!"

class PetDog(Animal, Dog): # Multiple Inheritance


def friendly(self):
return "Wags tail"

pet = PetDog()
print(pet.speak()) # Inherited from Animal
print(pet.bark()) # Inherited from Dog
print(pet.friendly()) # Own method
PetDog inherits from both Animal and Dog.

Memory Management
• PHP & JavaScript: Automatic garbage collection (Managed by the
interpreter)
• Java: Uses Garbage Collection (GC runs in the background)
• Python: Uses reference counting and garbage collection

• Java has an automatic garbage collector but allows manual hints (System.gc()).

System.gc(); // Requests garbage collection (JVM decides when to run it)


Python uses reference counting and garbage collection.
import gc
gc.collect() # Manually trigger garbage collection
PHP uses automatic garbage collection.
gc_collect_cycles(); // Runs garbage collection

Exception Handling
Exception handling prevents a program from crashing due to runtime errors.
In c++:
Uses keyword try, catch, throw
Example:
#include <iostream>
using namespace std;
int main() {
try {
throw "An error occurred!";
} catch (const char* msg) {
cout << "Caught exception: " << msg << endl;
}
return 0;
}
Exception Handling in Java
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("This always executes");
}

• Java uses try-catch-finally.

Exception Handling in Python


try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero")
finally:
print("This always executes")

try-except-finally.
Exception Handling in PHP
<?php
try {
echo 10 / 0; }
catch (DivisionByZeroError $e) {
echo "Error: Division by zero";
} finally {echo "This always executes";}
?>
JavaScript does not throw an error for division by zero (returns Infinity).

Operator Overloading
Redefining operators (+, -, *, etc.) for custom objects.

• Supported: Python,c++
• Not supported: Java, JavaScript, PHP
In c++
Uses keyword operator +
Example
#include <iostream>
using namespace std;
class Complex {
public:
int real, imag;
Complex(int r, int i) {
real = r;
imag = i;
}
Complex operator+(Complex c) { // Overloading +
return Complex(real + c.real, imag + c.imag);
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(2, 3), c2(4, 5);
Complex c3 = c1 + c2; // Calls operator+
c3.display();
return 0;
}
Operator Overloading in Python

class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other): # Overloading `+` operator


return Vector(self.x + other.x, self.y + other.y)

def __str__(self):
return f"({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(4, 5)
result = v1 + v2
print(result)
Python allows overloading operators like +, -, *, etc.

Encapsulation:
Encapsulation is the OOP principle of restricting direct access to object data and only
allowing modifications via methods (getters and setters). This helps maintain data
integrity and control.
In c++

#include <iostream>
using namespace std;
class BankAccount {
private:
double balance; // Private variable (cannot be accessed directly)
public:
// Constructor
BankAccount(double initialBalance) {
if (initialBalance < 0)
balance = 0;
else
balance = initialBalance;
}
// Setter: Deposits money
void deposit(double amount) {
if (amount > 0)
balance += amount;
}
// Setter: Withdraws money (with validation)
void withdraw(double amount) {
if (amount > 0 && amount <= balance)
balance -= amount;
else
cout << "Insufficient balance!" << endl;
}

// Getter: Retrieves the balance


double getBalance() {
return balance;
}
};

int main() {
BankAccount account(1000); // Initial balance = $1000

account.deposit(500); // Adding $500


account.withdraw(300); // Withdrawing $300

cout << "Final Balance: $" << account.getBalance() << endl;


return 0;
}

1. The balance variable is private, meaning it cannot be modified directly from


outside the class.
2. deposit() and withdraw() control how balance is updated, ensuring
data integrity.
3. getBalance() provides read-only access to balance.

Encapsulation in Java (Fully Supported)

In Java, encapsulation is achieved using:


Private variables (private)
Public getter and setter methods
Access control with public, private, protected

class BankAccount {
private double balance; // Private variable (cannot be accessed directly)
// Constructor
public BankAccount(double initialBalance) {
if (initialBalance < 0)
balance = 0;
else
balance = initialBalance;
}
// Setter method
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
// Setter method
public void withdraw(double amount) {
if (amount > 0 && amount <= balance)
balance -= amount;
else
System.out.println("Insufficient balance!");
}
// Getter method
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
account.deposit(500);
account.withdraw(300);
System.out.println("Final Balance: $" + account.getBalance());
}
}

Private balance variable → Cannot be accessed directly


Getter getBalance() → Allows read-only access
Setters deposit() & withdraw() → Validate updates

Encapsulation in JavaScript (Limited Support)


JavaScript does not have true private variables but uses closures (# syntax in ES6) or
conventions (_var).
Example: Encapsulation in JavaScript (Using # Private Fields)
class BankAccount {
#balance; // Private field (new in ES6)

constructor(initialBalance) {
this.#balance = initialBalance > 0 ? initialBalance : 0;
}
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
withdraw(amount) {
if (amount > 0 && amount <= this.#balance)
this.#balance -= amount;
else
console.log("Insufficient balance!");
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(1000);
account.deposit(500);
account.withdraw(300);
console.log("Final Balance: $" + account.getBalance());

Private field #balance (ES6 feature) prevents direct access


Methods (deposit, withdraw) control balance updates
Older JavaScript versions use _balance convention instead

Encapsulation in PHP (Supported)


PHP uses private and public access modifiers, similar to Java.
<?php
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = ($initialBalance > 0) ? $initialBalance : 0;
}
public function deposit($amount) {
if ($amount > 0) $this->balance += $amount;
}
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance)
$this->balance -= $amount;
else
echo "Insufficient balance!\n";
}
public function getBalance() {
return $this->balance;
}
}
// Usage
$account = new BankAccount(1000);
$account->deposit(500);
$account->withdraw(300);
echo "Final Balance: $" . $account->getBalance();
?>

Private $balance → Cannot be accessed directly


Getter getBalance() → Provides read-only access
Setters deposit() & withdraw() → Validate updates

Encapsulation in Python (Limited)


Python does not enforce private variables but uses naming conventions (_var or __var).
class BankAccount:
def __init__(self, initial_balance):
self.__balance = initial_balance if initial_balance > 0 else 0 # Private variable
(__balance)
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient balance!")
def get_balance(self):
return self.__balance
# Usage
account = BankAccount(1000)
account.deposit(500)
account.withdraw(300)
print("Final Balance: $", account.get_balance())

Double underscore (__balance) makes it “private”


Still accessible via _classname__balance (not truly private)
Encapsulation enforced via get_balance() and withdraw()

Which language provides the most flexible OOP implementation?


• Python → Flexible due to dynamic typing, multiple inheritance, and
easy syntax.
• Java → Strict but well-structured OOP.
• C++ → Powerful but complex.
• PHP → Good for web development but not purely OOP.
• JavaScript → Prototype-based, different from traditional OOP.
Which language is the easiest to use for OOP and why?
• Python is the easiest due to its simple syntax and dynamic typing.
• Java is also structured and widely used for enterprise applications.
• C++ is powerful but complex due to manual memory management.
• PHP and JavaScript are primarily web-focused.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy