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;
}
}