Object-Oriented Programming (OOP) -
Notes
1. Introduction to OOP
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
objects, which can contain data (fields/attributes) and methods (functions/behavior). It
focuses on reusability, modularity, and abstraction to solve complex problems.
2. Key Features of OOP
- Encapsulation: Binding data and methods into a single unit (class). Controls access using
access modifiers.
- Abstraction: Hiding implementation details and showing only essential features.
- Inheritance: Acquiring properties and behaviors of one class into another. Promotes
reusability.
- Polymorphism: Ability of an object to take many forms. Achieved via method overloading
and overriding.
3. Class and Object
Class: A blueprint for creating objects. Defines attributes (variables) and methods
(functions).
Object: An instance of a class that has real values assigned to attributes.
Example (in Java):
class Car {
String color;
void drive() { System.out.println("Driving..."); }
}
Car obj = new Car(); // creating object
4. Constructors & Destructors
Constructor: Special method invoked automatically when an object is created. Used for
initialization.
Destructor: Method that is invoked when an object is destroyed (e.g., finalize() in Java,
__del__ in Python).
5. Types of Inheritance
- Single Inheritance: One class inherits from another.
- Multilevel Inheritance: Class inherits from another derived class.
- Hierarchical Inheritance: Multiple classes inherit from a single parent.
- Multiple Inheritance: A class inherits from more than one parent (allowed in C++, not
directly in Java).
6. Polymorphism
- Compile-time Polymorphism: Method overloading (same method name, different
parameters).
- Run-time Polymorphism: Method overriding (child class provides specific implementation
of parent method).
7. Abstraction
Implemented using abstract classes and interfaces.
- Abstract class: Can have abstract methods (without body) and concrete methods.
- Interface: Defines a contract. Classes implementing interfaces must provide method
definitions.
8. Encapsulation
Wrapping of data and code together. Achieved using private fields and public getter/setter
methods.
Example in Java:
class Student {
private int age;
public void setAge(int a) { age = a; }
public int getAge() { return age; }
}
9. Advantages of OOP
- Modularity: Code can be divided into classes.
- Reusability: Inheritance promotes reuse.
- Scalability: Easier to manage large programs.
- Security: Encapsulation protects data.
- Flexibility: Polymorphism allows dynamic method behavior.