Classes and Constructors

Loading concept...

Classes and Constructors: Building Your Own LEGO Factory 🏭

Imagine you have a magical LEGO factory. This factory has a blueprint that tells it exactly how to build toys. Every toy that comes out looks similar but can have different colors or sizes. That’s exactly what Classes and Constructors are in Java!


OOP Fundamentals: The Big Idea

Object-Oriented Programming (OOP) is like organizing your toy room. Instead of throwing everything in one big box, you group similar things together.

Think of it this way:

  • All your toy cars go in the “car box”
  • All your dolls go in the “doll box”
  • All your building blocks go in the “blocks box”

Why is this smart?

  • Easy to find things
  • Easy to add new toys
  • Easy to share with friends

In Java, we organize our code the same way. We group related things together using classes.


Classes and Objects: The Blueprint and the Toy

What is a Class?

A class is like a cookie cutter or a blueprint.

It tells Java:

  • What things your object will have (called fields)
  • What actions your object can do (called methods)
class Dog {
    String name;
    int age;

    void bark() {
        System.out.println("Woof!");
    }
}

This blueprint says: “A Dog has a name, an age, and can bark.”

What is an Object?

An object is the actual toy made from the blueprint.

You can make many dogs from one Dog class:

  • One dog named “Buddy” who is 3 years old
  • Another dog named “Max” who is 5 years old

They all came from the same blueprint, but each one is unique.

graph TD A[Dog Class<br/>Blueprint] --> B[buddy object<br/>name: Buddy<br/>age: 3] A --> C[max object<br/>name: Max<br/>age: 5] A --> D[luna object<br/>name: Luna<br/>age: 2]

Object Instantiation: Making Real Toys

Instantiation is a fancy word for “making a real object from a class.”

Think of it like this:

  • Class = Recipe for chocolate chip cookies
  • Object = The actual cookie you eat

How to Create an Object

Use the magic word new:

Dog buddy = new Dog();
buddy.name = "Buddy";
buddy.age = 3;
buddy.bark();  // Prints: Woof!

Breaking it down:

  1. Dog buddy - “I want a Dog, and I’ll call it buddy”
  2. new Dog() - “Make a new Dog right now!”
  3. buddy.name = "Buddy" - “This dog’s name is Buddy”

Every time you use new, Java creates a fresh object in memory.


Constructors: The Welcome Party

When a new object is born, wouldn’t it be nice if someone said “Welcome!” and set things up?

That’s what a constructor does!

What is a Constructor?

A constructor is a special method that runs automatically when you create an object.

Rules for constructors:

  • Same name as the class
  • No return type (not even void)
  • Runs automatically when you say new
class Dog {
    String name;
    int age;

    // Constructor - welcome party!
    Dog() {
        System.out.println("A new dog is born!");
    }
}

Now when you write:

Dog buddy = new Dog();

Java automatically prints: “A new dog is born!”

Constructor with Parameters

What if we want to name the dog right away?

class Dog {
    String name;
    int age;

    Dog(String dogName, int dogAge) {
        name = dogName;
        age = dogAge;
        System.out.println(name + " is born!");
    }
}

Now you can write:

Dog buddy = new Dog("Buddy", 3);
// Prints: Buddy is born!

One line does everything!


Constructor Overloading: Multiple Welcome Options

Sometimes you want different ways to create an object.

Like ordering pizza:

  • “I want a pizza” (default size, default toppings)
  • “I want a large pizza” (specific size)
  • “I want a large pepperoni pizza” (size + toppings)

This is called constructor overloading - having multiple constructors with different parameters.

class Pizza {
    String size;
    String topping;

    // No parameters - default pizza
    Pizza() {
        size = "medium";
        topping = "cheese";
    }

    // One parameter - custom size
    Pizza(String pizzaSize) {
        size = pizzaSize;
        topping = "cheese";
    }

    // Two parameters - fully custom
    Pizza(String pizzaSize, String pizzaTopping) {
        size = pizzaSize;
        topping = pizzaTopping;
    }
}

Using it:

Pizza p1 = new Pizza();
// size: medium, topping: cheese

Pizza p2 = new Pizza("large");
// size: large, topping: cheese

Pizza p3 = new Pizza("large", "pepperoni");
// size: large, topping: pepperoni

Java picks the right constructor based on what you give it!


The this Keyword: “I Mean ME!”

What happens when parameter names match field names?

class Dog {
    String name;

    Dog(String name) {
        name = name;  // Confusing! Which name?
    }
}

This is confusing! Java doesn’t know which name you mean.

this to the Rescue!

The word this means “the current object” or “me, myself.”

class Dog {
    String name;

    Dog(String name) {
        this.name = name;
        // this.name = my field
        // name = the parameter
    }
}

Now it’s crystal clear:

  • this.name = “My name field”
  • name = “The name you gave me”

Other Uses of this

Calling another constructor:

class Dog {
    String name;
    int age;

    Dog() {
        this("Unknown", 0);
        // Calls the other constructor
    }

    Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

The this() call must be the first line in the constructor!


Initialization Blocks: Setup Before the Party

Sometimes you want code to run before any constructor.

There are two types:

Instance Initialization Block

Runs every time you create an object, before the constructor.

class Dog {
    String name;
    int energy;

    // Instance block - runs first!
    {
        energy = 100;
        System.out.println("Setting up...");
    }

    Dog(String name) {
        this.name = name;
        System.out.println("Constructor runs!");
    }
}

When you write new Dog("Buddy"):

  1. “Setting up…” (block runs first)
  2. “Constructor runs!” (constructor runs second)

Static Initialization Block

Runs only once when the class is first loaded.

class Dog {
    static int totalDogs;

    // Static block - runs once ever
    static {
        totalDogs = 0;
        System.out.println("Dog class loaded!");
    }
}

This is perfect for one-time setup that all objects share.

graph TD A[Class Loads] --> B[Static Block Runs<br/>Once only] B --> C[Object Created] C --> D[Instance Block Runs] D --> E[Constructor Runs]

Singleton Pattern: Only One King!

Imagine a game where there can only be one king. No matter how many times you ask for the king, you always get the same one.

This is the Singleton Pattern.

Why Use Singleton?

  • Database connection (only need one)
  • Game settings (same settings everywhere)
  • Logger (one file to write to)

How to Build a Singleton

Three simple rules:

  1. Private constructor - Nobody can use new
  2. Private static instance - The one and only object
  3. Public static method - The only way to get it
class King {
    // The one king
    private static King theKing = null;

    private String name;

    // Private - nobody can call new
    private King() {
        name = "Arthur";
    }

    // The only way to get the king
    public static King getKing() {
        if (theKing == null) {
            theKing = new King();
        }
        return theKing;
    }
}

Using it:

King k1 = King.getKing();
King k2 = King.getKing();

// k1 and k2 are the SAME king!
System.out.println(k1 == k2);  // true

No matter how many times you call getKing(), you always get Arthur!

graph TD A[Request 1: getKing] --> B{Does king exist?} B -->|No| C[Create new King] C --> D[Return King Arthur] B -->|Yes| D E[Request 2: getKing] --> B F[Request 3: getKing] --> B

Putting It All Together

Let’s build a complete example with everything we learned:

class Robot {
    // Fields
    private String name;
    private int batteryLevel;
    private static int totalRobots = 0;

    // Static block - runs once
    static {
        System.out.println("Robot factory online!");
    }

    // Instance block - runs per robot
    {
        batteryLevel = 100;
        totalRobots++;
    }

    // Default constructor
    Robot() {
        this("Unnamed Robot");
    }

    // Main constructor
    Robot(String name) {
        this.name = name;
        System.out.println(this.name + " created!");
    }

    void introduce() {
        System.out.println("I am " + this.name);
    }
}

Testing it:

Robot r1 = new Robot("Optimus");
Robot r2 = new Robot();

r1.introduce();  // I am Optimus
r2.introduce();  // I am Unnamed Robot

Quick Summary

Concept What It Does
Class Blueprint for objects
Object Real thing made from class
Instantiation Creating object with new
Constructor Runs when object is created
Overloading Multiple constructors
this Refers to current object
Init Block Code before constructor
Singleton Only one object ever

You Did It!

You now understand how Java creates and organizes objects. Think of classes as your LEGO instruction booklets and objects as the actual builds you create. Constructors are your helpful assistants that set everything up just right!

Keep building, keep learning, and remember: every expert was once a beginner who never gave up!

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.