Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
2. Object-Oriented Programming
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

12. Classes & Instances Deep Dive

Learn how to structure complex classes, understand attributes, and manage state.

Java Programming: From Zero to Enterprise
2. Object-Oriented Programming
February 22, 2026
68
A

[!NOTE] A class isn't just a container for data. It actively manages its own internal State, protecting its variables from invalid manipulation.

Class Attributes

Class Attributes (often called Fields or Instance Variables) are variables declared directly inside the class block, but outside of any specific method.

Unlike local variables inside a method, which are destroyed the moment the method finishes, Instance Variables stay alive as long as the Object itself stays alive in memory.

public class Player {
    // These are Instance Variables. Every new Player object gets its own copy!
    String username;
    int health = 100; // Default starting value
    boolean isAlive = true;

    // A method that alters the Object's internal state
    public void takeDamage(int damage) {
        health = health - damage;
        System.out.println(username + " took damage! Health is now " + health);
        
        if (health <= 0) {
            isAlive = false;
            System.out.println(username + " has died.");
        }
    }
}

Modifying Multiple Instances

Because every object instantiated with new gets its own completely isolated copy of the instance variables, changing one object has absolutely zero effect on another.

public class Game {
    public static void main(String[] args) {
        Player p1 = new Player();
        p1.username = "HeroGuy";
        
        Player p2 = new Player();
        p2.username = "VillainBoss";
        
        // P2 attacks P1!
        p1.takeDamage(40);
        
        // Output proves isolation!
        System.out.println(p1.health); // Outputs 60
        System.out.println(p2.health); // Output 100 (Unaffected!)
    }
}

The 'static' Keyword Exception

What if you want all objects to share the exact same variable? For example, what if you want to track the total number of players currently connected to the server?

If you add the static keyword to a variable, it detaches from the individual objects and attaches to the Class itself. There is now only one copy of that variable in the entire application memory, shared by all objects.

public class Player {
    String username; // Every player gets their own
    static int globalPlayerCount = 0; // Shared across the entire app!
    
    public Player() {
        globalPlayerCount++; // Every time a new player is born, increment the global tracker!
    }
}

[!WARNING] Do not overuse static. It is effectively a Global Variable mechanism, which breaks the isolation principles of OOP. If multiple threads try to modify a static variable simultaneously, your application will experience catastrophic race conditions.

Instance State vs Shared State

Every object should normally own its own state. If you create three Player objects, each player should have a separate username, score, and health. Shared state through static should be used carefully because it affects the whole class, not one object.

Reference Variables Matter

Player first = new Player();
first.username = "Asha";

Player second = first;
second.username = "Ravi";

System.out.println(first.username); // Ravi

This surprises beginners. first and second are two references pointing to the same object. No new player was created on the second assignment.

Creating Two Real Objects

Player first = new Player();
first.username = "Asha";

Player second = new Player();
second.username = "Ravi";

Use new when you want a distinct object with its own fields.

Common Mistakes

  • Using static fields for values that should belong to each object.
  • Assuming assignment copies an object. It usually copies the reference.
  • Letting objects enter invalid states, such as negative health.
  • Forgetting that object fields can have defaults while local variables cannot be used before assignment.

Mini Practice

Create two Player objects. Change one player's score and prove the other score is unchanged. Then assign one reference to another and observe how both names point to the same object.

Practice Lab: Instance Independence

Prove that each object has its own instance fields.

  1. Create a Player class with name, score, and level.
  2. Create two separate players using new.
  3. Increase one player's score and level.
  4. Print both players and confirm the second player did not change.
  5. Assign one reference to another and observe how reference sharing differs.

Goal: Separate object identity from reference variables.

Revision Checkpoint

  • Instance field: Each object gets its own copy.
  • Static field: Shared at class level.
  • Reference: Variable that points to an object.
  • Assignment: Copies the reference, not the object itself.
  • Object state: Should stay valid after each operation.

Before the quiz: Explain what happens when two variables reference the same object.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Classes &amp; Instances
19 questions5 min
Lesson 2 of 10 in 2. Object-Oriented Programming
Previous in 2. Object-Oriented Programming
11. Introduction to Object-Oriented Programming
Next in 2. Object-Oriented Programming
13. Constructors
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories