Skip to content

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, a storage size, and a power 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 new keyword 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


← Back: OOP Concepts | Next: Attributes & Methods β†’