Classes vs Objects
Objects
An object is a fundamental concept in Object-Oriented Programming (OOP) that represents anything in the real world. Objects are defined by two main characteristics:
- Properties (What it has)
- Represent attributes or characteristics
- Implemented as variables/data members
- Examples: Television- width, height, color, brand name, current channel, volume level
- Behaviour (What it can do)
- Represent actions or operations
- Implemented as methods/functions
- Examples: Television- switch on/off, change channel, adjust volume
- Identity (What makes it unique)
- Unique identification during object lifetime
- Distinguished from other objects
- See Object Identity for details
Class
A class is the blueprint or design from which objects are created. Key points about classes:
-
Class vs Object Relationship
- Class = Design/Definition (logical)
- Object = Real instance (physical)
- Example analogies: Television- Circuit design → Actual TV
-
One-to-Many Relationship
- One class can create multiple objects
- All objects share the same design/structure
- Each object can have different property values
//class structure
class Television {
// Properties (data members)
int channel; // current channel number
int volume; // current volume level
// Behaviors (methods)
public void changeChannel(int newChannel) {
// implementation
}
public void changeVolume(int newVolume) {
// implementation
}
}
//object creation & usage
Television t = new Television(); // Create object
t.changeChannel(10); // Call method Memory Areas
- The class information (structure and methods) is stored once, in the Method Area
- A reference variable like
tis a local variable, so it lives in the method’s stack frame - The actual object is created on the heap by
new - Multiple objects can exist at the same time, and each object has its own copy of the properties (instance fields)
For details, see Stack and Heap Memory.