Computer ScienceNEB 2081
Write short note on class and object in OOPs with a real word example. [2.5+2.5]
5Answer
Class and Object in OOPs
Class
A class is a blueprint or template that defines the structure and behavior of objects in Object-Oriented Programming (OOP). It encapsulates data (attributes) and functions (methods) that operate on the data. A class does not occupy memory; instead, it serves as a model for creating objects.
Example:
Consider a real-world scenario of a car. A class named Car can be defined with attributes like brand, model, year, and color, and methods like start(), stop(), and accelerate(). This class acts as a template for creating different car objects.
Object
An object is an instance of a class. When a class is instantiated, memory is allocated, and an object is created with specific values for its attributes. Objects are the actual entities that perform operations defined in the class.
Example:
If we create an object myCar from the Car class, it could have specific values like:
brand = "Toyota"model = "Corolla"year = 2023color = "Red"
This object (myCar) is a concrete representation of the Car class.
Real-World Analogy
Think of a class as a cookie cutter, which defines the shape of cookies. An object is the actual cookie made using that cutter. Multiple cookies (objects) can be created from the same cutter (class), but each cookie can have different attributes (e.g., chocolate chip vs. vanilla).
Key Differences
| Class | Object |
|---|---|
| Blueprint/template for objects | Actual instance of a class |
| Does not occupy memory | Occupies memory |
| Defines attributes and methods | Contains specific data (values) |
Example: Car |
Example: myCar (Toyota Corolla) |
Code Example (Python)
# Class definition
class Car:
def __init__(self, brand, model, year, color):
self.brand = brand
self.model = model
self.year = year
self.color = color
def start(self):
print(f"{self.brand} {self.model} is starting.")
def stop(self):
print(f"{self.brand} {self.model} has stopped.")
# Creating an object (instance of Car)
myCar = Car("Toyota", "Corolla", 2023, "Red")
# Accessing object attributes and methods
print(f"Car details: {myCar.brand}, {myCar.model}, {myCar.year}, {myCar.color}")
myCar.start()
myCar.stop()
Output:
Car details: Toyota, Corolla, 2023, Red
Toyota Corolla is starting.
Toyota Corolla has stopped.
Discussion
Loading…