Drani Academy – Interview Question, Search Job, Tuitorials, Cheat Sheet, Project, eBook

Object-Oriented Programming

Tutorials – Object-Oriented Programming (OOPs)

 
Chapter 14: OOP in Different Programming Languages

 

Object-Oriented Programming (OOP) is a programming paradigm that has been implemented in a wide variety of programming languages. Each language may have its own unique approach to implementing OOP concepts, leading to different syntax, features, and design patterns. In this chapter, we will explore how OOP is employed in several popular programming languages, highlighting their strengths and distinctive features.

14.1. OOP in Java

Java is one of the most iconic Object-Oriented Programming languages. It was designed with OOP principles at its core, making it an ideal choice for understanding OOP concepts. Java’s OOP features include:

14.1.1. Classes and Objects

Java uses classes and objects as the fundamental building blocks of OOP. A class serves as a blueprint for objects, defining their attributes (fields) and behaviors (methods). Java enforces strong encapsulation by allowing you to specify access modifiers (public, private, protected) for class members.

public class Car {
    // Fields (attributes)
    private String make;
    private String model;
    
    // Constructor
    public Car(String make, String model) {
        this.make = make;
        this.model = model;
    }
    
    // Method
    public void startEngine() {
        System.out.println("Engine started.");
    }
}

 

14.1.2. Inheritance

Java supports single inheritance, where a class can inherit attributes and methods from one superclass (parent class). This promotes code reuse and the creation of hierarchies.

public class ElectricCar extends Car {
    // Additional fields and methods specific to ElectricCar
}

 

14.1.3. Polymorphism

Java implements polymorphism through method overriding and method overloading. Method overriding allows subclasses to provide their own implementation of methods defined in the superclass. Method overloading enables multiple methods with the same name but different parameter lists.

public class Bicycle {
    public void ride() {
        System.out.println("Riding a bicycle.");
    }
}
public class Motorcycle extends Bicycle {
    @Override
    public void ride() {
        System.out.println("Riding a motorcycle.");
    }
}

 

14.1.4. Encapsulation

Java enforces encapsulation through access modifiers like private, protected, and public. Encapsulation restricts direct access to class members, promoting data hiding and controlled access to object state.

14.1.5. Abstraction

Java supports abstraction by allowing you to define abstract classes and methods. Abstract classes cannot be instantiated and are meant to be subclassed. Abstract methods have no implementation in the superclass and must be implemented in the subclass.

public abstract class Shape {
    public abstract double calculateArea();
}

 

14.2. OOP in Python

Python is a dynamically typed, high-level programming language known for its readability and simplicity. Python’s OOP features include:

14.2.1. Classes and Objects

Python employs classes and objects as the core elements of OOP. Classes are created using the class keyword, and objects are instances of classes. Python allows both single and multiple inheritance.

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        pass
class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"
class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

 

14.2.2. Inheritance

Python supports both single and multiple inheritance. In multiple inheritance, a class can inherit from multiple base classes. Python’s dynamic typing and duck typing make it flexible and powerful.

class A:
    def method(self):
        return "A method"
class B:
    def method(self):
        return "B method"
class C(A, B):
    pass

 

14.2.3. Polymorphism

Python allows polymorphism through method overriding, similar to Java. Polymorphism enables objects of different classes to respond to the same method name.

class Bird:
    def speak(self):
        pass
class Duck(Bird):
    def speak(self):
        return "Quack!"
class Parrot(Bird):
    def speak(self):
        return "Squawk!"

 

14.2.4. Encapsulation

Python uses conventions rather than strict access modifiers for encapsulation. Attributes and methods prefixed with an underscore (e.g., _attribute) are considered non-public, although they can still be accessed.

class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # Protected attribute
    def _withdraw(self, amount):
        if amount <= self._balance:
            self._balance -= amount
    def get_balance(self):
        return self._balance

 

14.2.5. Abstraction

Python supports abstraction through abstract base classes provided by the abc module. Abstract base

classes define abstract methods that must be implemented by concrete subclasses. Python’s dynamic nature means that abstraction can also be achieved through conventions.

from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def calculate_area(self):
        pass
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    def calculate_area(self):
        return 3.14 * self.radius * self.radius

 

14.3. OOP in C++

C++ is an extension of the C programming language and provides powerful OOP capabilities. It offers features like classes, templates, and operator overloading.

14.3.1. Classes and Objects

C++ uses classes and objects as the foundation of OOP. It supports data encapsulation through access specifiers (public, private, and protected) and includes constructors and destructors for object initialization and cleanup.

class Rectangle {
public:
    Rectangle(int w, int h) : width(w), height(h) {}
    int area() { return width * height; }
private:
    int width;
    int height;
};

 

14.3.2. Inheritance

C++ supports single inheritance and multiple inheritance. Classes can inherit attributes and methods from one or more base classes.

class Shape {
public:
    virtual double area() { return 0; }
};
class Circle : public Shape {
public:
    Circle(double r) : radius(r) {}
    double area() { return 3.14 * radius * radius; }
private:
    double radius;
};

 

14.3.3. Polymorphism

C++ achieves polymorphism through virtual functions and function overloading. Virtual functions are declared in base classes and can be overridden by derived classes. Function overloading allows multiple functions with the same name but different parameter lists.

class Animal {
public:
    virtual void sound() { std::cout << "Animal sound" << std::endl; }
};
class Dog : public Animal {
public:
    void sound() { std::cout << "Woof!" << std::endl; }
};
class Cat : public Animal {
public:
    void sound() { std::cout << "Meow!" << std::endl; }
};

 

14.3.4. Encapsulation

C++ supports encapsulation through access specifiers. Data members declared as private are inaccessible from outside the class, promoting data hiding and controlled access.

14.3.5. Abstraction

C++ provides support for abstract classes and pure virtual functions. Abstract classes cannot be instantiated and serve as a blueprint for concrete derived classes.

class Shape {
public:
    virtual double area() = 0;
};
class Circle : public Shape {
public:
    Circle(double r) : radius(r) {}
    double area() { return 3.14 * radius * radius; }
private:
    double radius;
};

 

14.4. OOP in C#

C# is a modern, statically-typed language developed by Microsoft. It integrates OOP features and is the primary language for developing applications on the .NET framework.

14.4.1. Classes and Objects

C# uses classes and objects to implement OOP concepts. Classes define attributes (fields) and methods, while objects are instances of classes. C# enforces strong encapsulation with access modifiers.

public class Car {
    private string make;
    private string model;
    
    public Car(string make, string model) {
        this.make = make;
        this.model = model;
    }
    
    public void StartEngine() {
        Console.WriteLine("Engine started.");
    }
}

 

14.4.2. Inheritance

C# supports single inheritance, where a class can inherit attributes and methods from one superclass. It also includes interface-based inheritance, allowing a class to implement multiple interfaces.

public class ElectricCar : Car {
    // Additional fields and methods specific to ElectricCar
}

 

14.4.3. Polymorphism

C# achieves polymorphism through method overriding and method overloading. Virtual methods declared in base classes can be overridden in derived classes.

public class Animal {
    public virtual void Speak() {
        Console.WriteLine("Animal sound");
    }
}
public class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Woof!");
    }
}
public class Cat : Animal {
    public override void Speak() {
        Console.WriteLine("Meow!");
    }

 

14.4.4. Encapsulation

C# enforces encapsulation through access modifiers (public, private, protected, etc.) to control access to class members. Encapsulation promotes data hiding and the principle of least privilege.

14.4.5. Abstraction

C# supports abstraction through abstract classes and interfaces. Abstract classes define abstract methods that must be implemented by derived classes. Interfaces provide a contract that classes can adhere to.

public abstract class Shape {
    public abstract double CalculateArea();
}
public class Circle : Shape {
    private double radius;
    
    public Circle(double r) {
        radius = r;
    }
    
    public override double CalculateArea() {
        return Math.PI * radius * radius;
    }
}

 

14.5. OOP in JavaScript

JavaScript is primarily known as a prototype-based programming language, but it also incorporates OOP features through constructor functions and prototype chains.

14.5.1. Constructor Functions

JavaScript uses constructor functions to create objects. These functions serve as blueprints for objects, allowing you to define attributes and methods for object instances.

function Person(name) {
    this.name = name;
}
Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
};
const john = new Person("John");
john.greet(); // Outputs: Hello, my name is John

 

14.5.2. Inheritance

JavaScript implements inheritance through prototype chains. Objects inherit properties and methods from their prototype object. By setting the prototype of a constructor function, you can establish an inheritance relationship.

function Animal() {}
Animal.prototype.speak = function() {
    console.log("Animal sound");
};
function Dog() {}
Dog.prototype = new Animal();
Dog.prototype.speak = function() {
    console.log("Woof!");
};
const myDog = new Dog();
myDog.speak(); // Outputs: Woof!

 

 

14.5.3. Polymorphism

Polymorphism in JavaScript is achieved through method overriding. Subclasses can override methods defined in their prototypes to provide their own implementations.

function Animal() {}
Animal.prototype.speak = function() {
    console.log("Animal sound");
};
function Dog() {}
Dog.prototype = new Animal();
Dog.prototype.speak = function() {
    console.log("Woof!");
};
function Cat() {}
Cat.prototype = new Animal();
Cat.prototype.speak = function() {
    console.log("Meow!");
};
const pets = [new Dog(), new Cat()];
pets.forEach(function(pet) {
    pet.speak();
});

 

14.5.4. Encapsulation

JavaScript supports encapsulation to some extent through closures. You

can use closures to create private variables and methods within constructor functions, limiting their access from the outside.

function Counter() {
    let count = 0; // Private variable
    
    this.increment = function() {
        count++;
    };
    
    this.getCount = function() {
        return count;
    };
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // Outputs: 1

 

14.5.5. Abstraction

JavaScript doesn’t have built-in abstract classes or interfaces like some other languages. However, you can achieve abstraction through conventions and by providing clear specifications for the expected methods in your objects.

14.6. OOP in Ruby

Ruby is a dynamically-typed, object-oriented programming language known for its simplicity and elegance. Ruby’s OOP features include:

14.6.1. Classes and Objects

In Ruby, everything is an object, and classes define objects. You can easily create classes, define attributes, and implement methods.

class Person
  def initialize(name)
    @name = name
  end
  def greet
    puts "Hello, my name is #{@name}"
  end
end
john = Person.new("John")
john.greet

 

14.6.2. Inheritance

Ruby supports single inheritance, where a class can inherit from one superclass. Classes can also include modules, which are similar to multiple inheritance.

class Animal
  def speak
    puts "Animal sound"
  end
end
class Dog < Animal
  def speak
    puts "Woof!"
  end
end
class Cat < Animal
  def speak
    puts "Meow!"
  end
end
my_dog = Dog.new
my_dog.speak

 

 

14.6.3. Polymorphism

Polymorphism in Ruby is straightforward. Subclasses can override methods defined in their superclass. Method overloading is not supported because Ruby supports dynamic typing.

class Animal
  def speak
    puts "Animal sound"
  end
end
class Dog < Animal
  def speak
    puts "Woof!"
  end
end
class Cat < Animal
  def speak
    puts "Meow!"
  end
end
pets = [Dog.new, Cat.new]
pets.each { |pet| pet.speak }

 

 

14.6.4. Encapsulation

Ruby enforces encapsulation by allowing you to control the visibility of attributes and methods using access specifiers (public, private, protected).

class BankAccount
  def initialize(balance)
    @balance = balance  # Private attribute
  end
  def withdraw(amount)
    if amount <= @balance
      @balance -= amount
    end
  end
  def get_balance
    @balance
  end
end

 

 

 

14.6.5. Abstraction

Ruby supports abstraction through the use of abstract classes and methods. You can create abstract classes by raising an exception in the abstract method’s definition.

class Shape
  def calculate_area
    raise "Abstract method: calculate_area"
  end
end
class Circle < Shape
  def initialize(radius)
    @radius = radius
  end
  def calculate_area
    Math::PI * @radius**2
  end
end

 

 

 

14.7. OOP in Swift

Swift is a statically-typed, multi-paradigm language developed by Apple for iOS, macOS, watchOS, and tvOS development. Swift incorporates OOP features alongside functional programming capabilities.

14.7.1. Classes and Objects

Swift uses classes and objects as the core building blocks for OOP. Classes define attributes (properties) and behaviors (methods). Swift is known for its safety features, which help prevent runtime errors.

class Person {
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func greet() {
        print("Hello, my name is \(name)")
    }
}
let john = Person(name: "John")
john.greet()

 

 

14.7.2. Inheritance

Swift supports single inheritance, where a class can inherit from one superclass. Inheritance enables code reuse and the creation of hierarchies.

class Animal {
    func speak() {
        print("Animal sound")
    }
}
class Dog: Animal {
    override func speak() {
        print("Woof!")
    }
}
class Cat: Animal {
    override func speak() {
        print("Meow!")
    }
}
let myDog = Dog()
myDog.speak()

 

 

 

 

14.7.3. Polymorphism

Polymorphism is implemented in Swift through method overriding. Subclasses can provide their own implementation of methods defined in their superclass.

class Animal {
    func speak() {
        print("Animal sound")
    }
}
class Dog: Animal {
    override func speak() {
        print("Woof!")
    }
}
class Cat: Animal { override func speak() { print("Meow!") } }
let pets: [Animal] = [Dog(), Cat()]
for pet in pets { pet.speak() }

 

 

 

14.7.4. Encapsulation

Swift supports encapsulation through access control. You can use access modifiers like `private`, `internal`, `public`, and `open` to control the visibility of properties and methods.

class BankAccount {
    private var balance: Double
    
    init(balance: Double) {
        self.balance = balance
    }
    
    func withdraw(amount: Double) {
        if amount <= balance {
            balance -= amount
        }
    }
    
    func getBalance() -> Double {
        return balance
    }
}

14.7.5. Abstraction

Swift encourages abstraction through protocol-oriented programming. You can define protocols with method requirements that must be implemented by conforming types.

protocol Shape {
    func calculateArea() -> Double
}
struct Circle: Shape {
    var radius: Double
    
    func calculateArea() -> Double {
        return Double.pi * radius * radius
    }
}

 

14.8. OOP in PHP

PHP is a popular server-side scripting language that includes OOP features, making it suitable for web development.

14.8.1. Classes and Objects

PHP supports classes and objects as the foundation of OOP. Classes define properties and methods, while objects are instances of classes. PHP also allows constructor and destructor methods.

class Person {
    public $name;
    
    public function __construct($name) {
        $this->name = $name;
    }
    
    public function greet() {
        echo "Hello, my name is {$this->name}";
    }
}
$john = new Person("John");
$john->greet();

 

14.8.2. Inheritance

PHP supports single inheritance, where a class can inherit from one parent class. Inheritance promotes code reuse and hierarchy creation.

class Animal {
    public function speak() {
        echo "Animal sound";
    }
}
class Dog extends Animal {
    public function speak() {
        echo "Woof!";
    }
}
class Cat extends Animal {
    public function speak() {
        echo "Meow!";
    }
}
$myDog = new Dog();
$myDog->speak();

 

 

 

14.8.3. Polymorphism

Polymorphism in PHP is implemented through method overriding. Subclasses can override methods defined in their parent class.

class Animal {
    public function speak() {
        echo "Animal sound";
    }
}
class Dog extends Animal {
    public function speak() {
        echo "Woof!";
    }
}
class Cat extends Animal {
    public function speak() {
        echo "Meow!";
    }
}
$pets = [new Dog(), new Cat()];
foreach ($pets as $pet) {
    $pet->speak();
}

 

 

 

 

14.8.4. Encapsulation

PHP supports encapsulation through access modifiers like public, protected, and private. These modifiers control access to properties and methods.

class BankAccount {
    private $balance;
    
    public function __construct($balance) {
        $this->balance = $balance;
    }
    
    public function withdraw($amount) {
        if ($amount <= $this->balance) {
            $this->balance -= $amount;
        }
    }
    
    public function getBalance() {
        return $this->balance;
    }
}

14.8.5. Abstraction

PHP supports abstraction through interfaces. Interfaces define method signatures that implementing classes must adhere to.

interface Shape {
    public function calculateArea();
}
class Circle implements Shape {
    private $radius;
    
    public function __construct($radius) {
        $this->radius = $radius;
    }
    
    public function calculateArea() {
        return 3.14 * $this->radius * $this->radius;
    }
}

 

14.9. OOP in C

C is a procedural programming language, but object-oriented concepts can be simulated in C through struct-based data structures and function pointers.

14.9.1. Structs and Function Pointers

In C, you can use structs to group related data and function pointers to simulate methods. This approach can mimic some aspects of OOP.

typedef struct {
    char name[50];
    void (*greet)(const char*);
} Person;
void greetPerson(const char* name) {
    printf("Hello, my name is %s\n", name);
}
int main() {
    Person john;
    strcpy(john.name, "John");
    john.greet = greetPerson;
    john.greet(john.name);
    return 0;
}

 

 

 

While C doesn’t natively support inheritance, polymorphism, or encapsulation, these features can be manually implemented using C’s procedural paradigm.

14.10. OOP in Go

Go is a statically-typed, compiled language that emphasizes simplicity and efficiency. While not a pure object-oriented language, Go supports OOP-like features through struct types and methods.

14.10.1. Structs and Methods

Go uses structs to define data structures and methods to associate functions with types. While it lacks classical inheritance, it supports composition.

package main
import "fmt"
type Person struct {
    Name string
}
func (p Person) Greet() {
    fmt.Printf("Hello, my name is %s\n", p.Name)
}
func main() {
    john := Person{Name: "John"}
    john.Greet()
}

 

 

 

 

Go promotes simplicity and follows a “composition over inheritance” philosophy.

14.11. Conclusion

Object-Oriented Programming is a versatile paradigm that can be implemented in various programming languages, each with its own unique approach. Whether you choose Java’s strong OOP support, Python’s flexibility, C++’s power, C#’s integration with .NET, JavaScript’s prototype-based approach, Ruby’s elegance, Swift’s safety and performance, PHP’s web development capabilities, C’s simplicity, or Go’s efficiency, OOP principles can be applied effectively.

Selecting the right programming language for your project depends on your specific requirements, team expertise, and project constraints. Understanding how each language incorporates OOP can help you make informed decisions and design effective software systems.

 

Scroll to Top