Classes and Objects π¶
Mentor's Note: In Java, you can't just write a line of code in the middle of nowhere. Everything must live inside a Class. Itβs the "Home" for your code! π‘
π The Scenario: The Smartphone Factory π¶
Imagine you own a factory that makes smartphones.
- The Class (The Blueprint): Before making any phone, engineers create a detailed design π. This design says every phone must have a
color, astorage size, and apower button. π¦ - The Object (The actual Phone): Using that blueprint, the factory produces an actual iPhone π±. One is Space Grey (Object 1), another is Gold (Object 2).
- The Result: You can't make a call using the blueprint; you need the actual object! β
π Concept Explanation¶
1. What is a Class?¶
A class is a template or blueprint that describes the behavior/state that the object of its type supports.
2. What is an Object?¶
An object is an instance of a class. It has state (variables) and behavior (methods).
3. The new Keyword ποΈ¶
The new keyword is the "Start Button" of your factory. It tells Java to allocate memory and create a real object from your class blueprint.
π¨ Visual Logic: Blueprint to Reality¶
graph TD
subgraph Blueprint: ["Class: Smartphone π"]
A[Variable: Color]
B[Method: call()]
end
Blueprint -- "new keyword" --> O1["Object: My iPhone π± (Space Grey)"]
Blueprint -- "new keyword" --> O2["Object: Your Galaxy π± (Gold)"]
π» Implementation: The Factory Lab¶
// π Scenario: Building a Phone
// π Action: Creating a class and object
class Smartphone {
String model = "Pro Max"; // π¦ Attribute (State)
void ring() { // βοΈ Method (Behavior)
System.out.println("Beep! Beep! π");
}
}
public class Main {
public static void main(String[] args) {
// ποΈ Step 1: Instantiate the Object
Smartphone myPhone = new Smartphone();
// π·οΈ Step 2: Access properties
System.out.println("Model: " + myPhone.model);
// π Step 3: Call methods
myPhone.ring();
}
}
π Sample Dry Run¶
| Step | Instruction | Memory State | Result |
|---|---|---|---|
| 1 | Smartphone myPhone |
null |
Reference created π₯ |
| 2 | = new Smartphone(); |
Memory@101 |
Object born! ποΈ |
| 3 | myPhone.ring(); |
Running method | Output: Beep! π€ |
π Technical Analysis¶
- Class: Logical entity. No memory is allocated when a class is defined.
- Object: Physical entity. Memory is allocated as soon as the
newkeyword is used. πΎ
π― Practice Lab π§ͺ¶
Task: The Car Garage
Task: Create a class Car with attributes color and speed. Create two different car objects (one "Red", one "Blue") and print their details.
Hint: Use the new keyword twice! π‘
π‘ Pro Tip: "Classes are the skeleton, Objects are the body. You need the skeleton to build the body!" - Vishnu Damwala