Constructing Code to Define Classes and Instantiate Objects
Understanding Classes and Objects
What is a Class?
- A class is a blueprint or template for creating objects.
- It defines the attributes (instance variables) and methods (behaviors) that the objects will have.
- A class is like a blueprint for a house.
- It defines the structure and features, but no actual house exists until you build one using the blueprint.
What is an Object?
- An object is an instance of a class.
- It is a concrete entity that exists in memory, with its own set of attribute values.
- An object is like a specific house built from a blueprint.
- Each house (object) can have different colors, furniture, and decorations (attribute values), but they all share the same basic structure defined by the blueprint (class).
Defining Classes
Structure of a Class
- Class Declaration
- Specifies the name of the class.
- Often begins with the class keyword.
- Instance Variables (Attributes/Fields)
- Represent the state or properties of the class.
- Each object created from the class has its own copy of these variables.
- Methods (Behaviors/Functions)
- Define the actions or operations the class can perform.
- Can manipulate instance variables or perform other logic.
- In Java, the filename and class name must match.
- In Python, this is a recommended practice but not a requirement.
Bird Class
Python:
# Class Declaration
class Bird:
# Constructor with instance variables
def __init__(self, species, age):
self.species = species
self.age = age
# Method (Behavior)
def sing(self):
print(f"{self.species} is singing!")
# Accessor
def get_age(self):
return self.ageJava:
// Class Declaration
public class Bird {
// Instance Variables
private String species;
private int age;
// Constructor
public Bird(String species, int age) {
this.species = species;
this.age = age;
}
// Method (Behavior)
public void sing() {
System.out.println(species + " is singing!");
}
// Accessor
public int getAge() {
return age;
}
}Note the use ofthis in Java and selfin Python to refer to instance variables.
Instantiating Objects
What is Instantiation?
- Instantiation is the process of creating an object from a class.
- It involves calling the constructor method, which initializes the object’s attributes (state).
- Each object created from the same class is independent and has its own copy of the instance variables.
Creating Bird Objects
Python:
# Instantiating objects using the Bird class constructor
sparrow = Bird("Sparrow", 2)
parrot = Bird("Parrot", 5)
# Calling methods on objects
sparrow.sing() # Output: Sparrow is singing!
print("Parrot age:", parrot.get_age()) # Output: Parrot age: 5Java:
public class Main {
public static void main(String[] args) {
// Instantiating objects using the Bird class constructor
Bird sparrow = new Bird("Sparrow", 2);
Bird parrot = new Bird("Parrot", 5);
// Calling methods on objects
sparrow.sing(); // Output: Sparrow is singing!
System.out.println("Parrot age: " + parrot.getAge()); // Output: Parrot age: 5
}
}- In Java, instantiation occurs within a method, typically main.
- In Python, it can happen anywhere in the script.
The Role of Constructors
What is a Constructor?
- A constructor is a special method that initializes an object's state.
- It sets the initial values for the object's attributes.
Key Features of Constructors
- Same Name as the Class: In Java, the constructor shares the class name. In Python, it is defined as __init__.
- No Return Type: Constructors do not have a return type.
- Automatic Invocation: Called automatically when an object is instantiated.
- In Java, if no constructor is defined, a default constructor is provided.
- In Python, you must define__init__if initialization is needed.
Plant Class: UML Diagram
| Plant |
|---|
| - scientificName: String |
| - scientificFamily: String |
| - distribution: String |
| - bloom: boolean |
| + getScientificName() |
| + getScientificFamily() |
| + getDistribution() |
| + getBloom() |
Key Takeaways
- Classes are blueprints for objects, defining attributes and methods.
- Objects are instances of classes, created through instantiation.
- Constructors initialize an object's state, setting initial values for attributes.
- What is the difference between a class and an object?
- How does a constructor initialize an object's state?
- Why is encapsulation important in object-oriented programming?