Introduction to OOP in Each Language-
Introduction to OOP in Each Language-
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
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++:
// 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();
}
}
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();
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.
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.
# 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();
class MathUtils {
int add(int a, int b) {
return a + b;
}
// 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();
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
# 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()
• 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;
}
<?php
// Abstract class
abstract class Animal {
public $name;
# 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;}
class Animal:
def speak(self):
return "Some sound"
class Dog:
def bark(self):
return "Woof!"
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()).
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");
}
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 __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;
}
int main() {
BankAccount account(1000); // Initial balance = $1000
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());
}
}
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());