⬅ Previous Topic
Choosing the Right Data StructureNext Topic ⮕
Encapsulation in Programming - OOP⬅ Previous Topic
Choosing the Right Data StructureNext Topic ⮕
Encapsulation in Programming - OOPIn programming, a class is a blueprint or template that defines the structure and behavior (data and functions) of objects. An object is an actual instance of a class—just like a real-world object with properties and actions.
Imagine a class as a recipe and an object as the actual dish prepared from that recipe.
Consider a "Car" as a class. All cars have certain properties like color, model, and engine type. They also have behaviors like drive, brake, and honk.
class Car:
attribute color
attribute model
method drive():
print "The car is driving."
method brake():
print "The car has stopped."
# Creating an object
myCar = new Car()
myCar.color = "Red"
myCar.model = "Sedan"
myCar.drive()
myCar.brake()
Output:
The car is driving. The car has stopped.
class Car
defines a blueprint for cars.attribute
defines the properties every car has.method
represents actions the car can perform.myCar
is an instance (object) created from the Car
class.Answer: You can create as many car objects as needed, each with its own unique state (color, model, etc.), but all sharing the same behavior (methods).
Let’s consider modeling a student:
class Student:
attribute name
attribute grade
method introduce():
print "Hi, my name is " + name + " and I am in grade " + grade
# Creating objects
student1 = new Student()
student1.name = "Alice"
student1.grade = "10"
student2 = new Student()
student2.name = "Bob"
student2.grade = "12"
student1.introduce()
student2.introduce()
Output:
Hi, my name is Alice and I am in grade 10 Hi, my name is Bob and I am in grade 12
Q: Can two objects have different values for the same attribute?
A: Yes, even though both are instances of the same class, their properties can have different values.
We’ll learn about constructors, the special methods used to initialize objects with default values upon creation.
⬅ Previous Topic
Choosing the Right Data StructureNext Topic ⮕
Encapsulation in Programming - OOPYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.