6.1 Classes and Objects
Java is a true Object-Oriented Programming (OOP) language. Modeling real-world objects or concepts into the form of a computer program 'object' is the core of object-oriented programming.
1. Definition of Class and Object
Class
- Definition: A blueprint or template that defines objects.
- Purpose: Used to create objects. (e.g., A waffle maker tool, a TV blueprint)
Object / Instance
- Definition: Something that actually exists (the physical entity created in memory by a class).
- Purpose: Used differently depending on the functionalities and properties it holds. (e.g., The cooked waffle, individual TV products being sold)
The process of creating a certain object from a class is called instantiation, and the resulting created object is referred to as an ** instance**of that class.
2. Components of an Object
An object consists of multiple properties and functions, which are defined within the class. In Java, they are specifically termed as follows:
- Property:
Member variable,Field - Function:
Method
Example of Writing a Class
class Tv {
// Properties (Member variables)
String color; // Color
boolean power; // Power state
int channel; // Channel number
// Functions (Methods)
void power() { power = !power; } // Turn power on/off
void channelUp() { channel++; } // Channel up
void channelDown() { channel--; }// Channel down
}
3. Creation and Usage of Objects
Merely declaring a class is insufficient; you must physically create an instance (object) to use its variables and methods effectively.
// 1. Declare a reference variable to handle the object
Tv t;
// 2. Create the actual object and store its memory address inside the references (Instantiation)
t = new Tv();
// Using the object
t.channel = 7; // Set the channel member variable of the Tv instance to 7.
t.channelDown(); // Execute the channelDown() method explicitly targeting the Tv instance.
System.out.println("The current channel is " + t.channel); // Outputs 6
The greatest characteristic of OOP is that once a class definition logic exists, you can mass-produce numerous independent instances infinitely whenever necessary. If you dynamically generate numerous divergent instances, each firmly maintains entirely separate properties (like color, channels) inherently isolated.