B3.1.4 Construct code to define classes and instantiate objects.
• How to define classes and create objects from those classes
• The role of constructors in initializing an object's state, setting initial values for its attributes to define its condition or characteristics at the time of creation
The big idea
In object-oriented programming, a class is like a blueprint, and an object is a real thing built from that blueprint.
To make a working program:
- Define a class – decide what data (attributes) and actions (methods) it should have.
- Create (instantiate) objects – use the class to make individual instances that each have their own data.
- Use a constructor – special code that runs when an object is created to set up its initial state.
Step 1: Defining a class
A class usually contains:
- Attributes – data stored in the object (e.g., name, age, balance).
- Methods – actions the object can perform.
Example:
class Dog:
def __init__(self, name, breed):
# Constructor sets initial state
self.name = name # instance attribute
self.breed = breed # instance attribute
def bark(self):
return f"{self.name} says: Woof!"
Step 2: Understanding the constructor
- In Python, the constructor is a method named
__init__. - In Java, it’s a method with the same name as the class (no return type).
- The constructor runs automatically when you create a new object from the class.
- It’s the perfect place to set the initial values for attributes, ensuring every object starts in a valid state.
Example in Java:
public class Dog {
private String name;
private String breed;
// Constructor
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
public String bark() {
return name + " says: Woof!";
}
}
Step 3: Instantiating objects
Python:
my_dog = Dog("Buddy", "Labrador")
print(my_dog.bark()) # Buddy says: Woof!
Java:
Dog myDog = new Dog("Buddy", "Labrador");
System.out.println(myDog.bark()); // Buddy says: Woof!
When you write Dog("Buddy", "Labrador") in Python or new Dog("Buddy", "Labrador") in Java:
- Memory is allocated for the object.
- The constructor runs, assigning
"Buddy"and"Labrador"to the new object’s attributes. - You get back a reference to the object, stored in a variable (
my_dogormyDog).
Why constructors are important
- Consistency: All objects start with valid, predictable data.
- Convenience: You can pass in setup information at creation time instead of setting each attribute manually after creation.
- Safety: Prevents use of objects before they are ready.
Example with multiple objects
dog1 = Dog("Max", "Beagle")
dog2 = Dog("Luna", "Poodle")
print(dog1.bark()) # Max says: Woof!
print(dog2.bark()) # Luna says: Woof!
Even though both dog1 and dog2 come from the same Dog class:
- Each has its own
nameandbreed. - Methods like
bark()use that object’s own data.
Common mistakes
- Forgetting
<strong>self</strong>in Python methods: Every instance method must haveselfas the first parameter. - Not using the constructor: Without it, you might end up with objects missing important initial values.
- Reusing one object instead of creating new ones: Each instance should represent a separate thing.