Object-Oriented Programming (OOP) Concepts with Java/Python
From the I'm a Diploma cst 2nd semester students. My exam in 30 days, curriculum
TL;DR
OOP is a programming style that organizes software design around data, or objects, rather than functions and logic. It helps manage complexity by bundling data and methods that operate on that data into single units. Mastering OOP concepts like classes, objects, inheritance, polymorphism, encapsulation, and abstraction is crucial for building robust and scalable applications.
1. The Mental Model
Think of OOP like building with LEGOs. Instead of building everything from scratch, you create reusable blocks (objects) that have specific properties (colors, shapes) and can do certain things (connect to other blocks). You then assemble these blocks to create a larger structure.
2. The Core Material
OOP is built around several key principles. We'll look at them using both Java and Python examples.
2.1. Classes and Objects

Photo by miniperde on Pexels
A class is a blueprint or a template for creating objects. It defines the properties (data/attributes) and behaviors (methods/functions) that objects of that class will have. An object is an instance of a class. You can create many objects from a single class blueprint.
Java Example:
// Class definition
class Dog {
// Attributes (properties)
String name;
String breed;
// Constructor (to create Dog objects)
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
// Method (behavior)
void bark() {
System.out.println(name + " says Woof!");
}
}
// Creating objects
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy", "Golden Retriever"); // Object 1
Dog anotherDog = new Dog("Lucy", "Beagle"); // Object 2
myDog.bark(); // Buddy says Woof!
anotherDog.bark(); // Lucy says Woof!
}
}
Python Example:
# Class definition
class Dog:
# Constructor (to create Dog objects)
def __init__(self, name, breed):
self.name = name # Attributes
self.breed = breed
# Method (behavior)
def bark(self):
print(f"{self.name} says Woof!")
# Creating objects
my_dog = Dog("Buddy", "Golden Retriever") # Object 1
another_dog = Dog("Lucy", "Beagle") # Object 2
my_dog.bark() # Buddy says Woof!
another_dog.bark() # Lucy says Woof!
2.2. Encapsulation
Encapsulation is about bundling data (attributes) and methods that operate on the data into a single unit (the class) and restricting direct access to some of an object's components. This is often achieved using access modifiers (like private in Java) and getter/setter methods. It protects data from accidental modification.
Java Example:
class Account {
private double balance; // Private attribute
public Account(double initialBalance) {
if (initialBalance >= 0) {
this.balance = initialBalance;
} else {
this.balance = 0;
}
}
// Getter method to read balance
public double getBalance() {
return balance;
}
// Setter method to modify balance (with validation)
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
Python Example:
Python doesn't have strict private keywords like Java. We use conventions (prefixing with _ or __) to indicate private attributes, but they can still be accessed. Property decorators are often used for controlled access.
class Account:
def __init__(self, initial_balance):
self.__balance = 0 # Convention for private
if initial_balance >= 0:
self.__balance = initial_balance
@property # Getter
def balance(self):
return self.__balance
def deposit(self, amount): # Setter-like method
if amount > 0:
self.__balance += amount
# acc = Account(100)
# print(acc.balance) # Access via property
# acc.deposit(50)
# print(acc.balance)
2.3. Inheritance
Inheritance allows a class (subclass/child class) to inherit properties and methods from another class (superclass/parent class). This promotes code reusability. The "is-a" relationship is key here (e.g., a Car is a Vehicle).
Java Example:
class Vehicle { // Parent class
String brand;
void honk() {
System.out.println("Beep!");
}
}
class Car extends Vehicle { // Child class inherits from Vehicle
String model;
void drive() {
System.out.println(brand + " " + model + " is driving.");
}
}
// Car myCar = new Car();
// myCar.brand = "Toyota";
// myCar.model = "Corolla";
// myCar.honk(); // Inherited method
// myCar.drive();
Python Example:
class Vehicle: # Parent class
def __init__(self, brand):
self.brand = brand
def honk(self):
print("Beep!")
class Car(Vehicle): # Child class inherits from Vehicle
def __init__(self, brand, model):
super().__init__(brand) # Call parent constructor
self.model = model
def drive(self):
print(f"{self.brand} {self.model} is driving.")
# my_car = Car("Toyota", "Corolla")
# my_car.honk() # Inherited method
# my_car.drive()
2.4. Polymorphism
Polymorphism means "many forms." It allows objects of different classes to be treated as objects of a common type. The most common forms are method overloading (same method name, different parameters) and method overriding (subclass provides a specific implementation of a method already defined in its superclass).
Java Example (Method Overriding):
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override // Annotation indicating overriding
void makeSound() {
System.out.println("Cat says Meow");
}
}
class DogP extends Animal { // Renamed to avoid clash with earlier Dog
@Override
void makeSound() {
System.out.println("Dog says Woof");
}
}
// Animal myAnimal = new Cat();
// myAnimal.makeSound(); // Cat says Meow
// myAnimal = new DogP();
// myAnimal.makeSound(); // Dog says Woof
Python Example (Method Overriding):
class Animal:
def make_sound(self):
print("Animal makes a sound")
class Cat(Animal):
def make_sound(self): # Overriding
print("Cat says Meow")
class DogP(Animal): # Renamed to avoid clash with earlier Dog
def make_sound(self): # Overriding
print("Dog says Woof")
# my_animal = Cat()
# my_animal.make_sound() # Cat says Meow
# my_animal = DogP()
# my_animal.make_sound() # Dog says Woof
2.5. Abstraction
Abstraction is about showing only essential information and hiding the complex implementation details. In Java, this is achieved using abstract classes and interfaces. In Python, abstract base classes (abc module) are used. You define what an object does, not how it does it.
Java Example (Abstract Class):
abstract class Shape { // Abstract class
String color;
abstract double getArea(); // Abstract method (no body)
void setColor(String color) { // Concrete method
this.color = color;
}
}
class Circle extends Shape {
double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double getArea() { // Must implement abstract method
return Math.PI * radius * radius;
}
}
// Shape myShape = new Circle(5);
// myShape.setColor("Red");
// System.out.println(myShape.getArea());
Python Example (Abstract Base Class - ABC):
from abc import ABC, abstractmethod
class Shape(ABC): # Abstract base class
def __init__(self, color):
self.color = color
@abstractmethod
def get_area(self): # Abstract method
pass
def set_color(self, color): # Concrete method
self.color = color
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def get_area(self): # Must implement abstract method
import math
return math.pi * self.radius ** 2
# my_shape = Circle("Red", 5)
# print(my_shape.get_area())
Here's how these concepts relate:
graph TD
A[OOP Core Concepts] --> B(Class & Object)
A --> C(Encapsulation)
A --> D(Inheritance)
A --> E(Polymorphism)
A --> F(Abstraction)
B --> G[Blueprint & Instance]
C --> H[Data Hiding & Protection]
D --> I[Code Reusability "is-a"]
E --> J[Many Forms: Overriding/Overloading]
F --> K[Hide Details, Show Essentials]
3. Worked Example
Let's model a simple online store's products using OOP. We'll have a base Product class and then specialized Book and Electronics classes.
Python Example:
```python
class Product:
def init(self, name, price, product_id):
self.name = name
self.price = price
self.product_id = product_id
def get_details(self):
return f"ID: {self.product_id}, Name: {self.name}, Price:
Frequently asked about Object-Oriented Programming (OOP) Concepts with Java/Python
Study this next
Get the full I'm a Diploma cst 2nd semester students. My exam in 30 days, curriculum
Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.
Save this course free