The General Nature of an Object
What Is an Object?
Objects in OOP represent real-world entities in a simplified form, allowing programs to manage their states (attributes) and define their behaviour (methods).
States/data (attributes)
These are the characteristics or properties of the object.
- For a Person object, attributes might include name, age, and height.
- For a Car object, attributes might include number of wheels, power source, brand.
Actions (methods)
These are functions the object can perform.
- For a Person object, methods might include walk, sleep, and talk.
- For a Car object, methods might include go forward, stop, turn.
In programming, attributes are often referred to as fields or properties, while methods are sometimes called functions or procedures.
- When designing objects, think about what data defines the entity and what actions it can perform.
- This helps create a clear and organised structure.
Understanding Objects and Classes
Class
A blueprint for creating objects, defining their data (attributes) and actions (methods).
As we cannot make classes do something, we need a process of
Instantiation
The process of creating a specific object from a class.
Hence, from the other side we can say that:
Object
A specific instance of a class, containing attributes and methods.
When an object is instantiated, memory is allocated to store its unique data and methods.
A class is like a blueprint for a house, while instantiation is the building process, and an object is a specific house built from that blueprint.
Short recap class vs object
| Class | Object |
|---|---|
| Abstract: Defines a template for objects | Concrete: A specific instance of a class |
| Does not occupy memory until instantiated | Occupies memory to store data and actions |
Do not mix them up!
class Vehicle { // define a class
// here are the attributes
String brand;
int wheels;
void start() { // method
System.out.println("Vehicle is starting");
}
public static void main(String[] args) {
Vehicle car = new Vehicle(); // instantiate first object
car.brand = "Toyota";
car.wheels = 4;
Vehicle truck = new Vehicle(); // instantiate second object
truck.brand = "Ford";
truck.wheels = 8;
// test the start method
car.start();
truck.start();
}
}
Why We Need Classes?
- Classes specify the attributes and methods that objects will have.
- They group related data and actions, promoting modularity and reusability.
- What are the key components of an object?
- How does abstraction help in designing objects?
- Can you think of a real-world entity that could be represented as an object in a program?
- What is the difference between a class and an object?
- How does instantiation relate to memory usage in a program?
- Why is it important to understand the distinction between classes and objects in OOP?