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.

Feb 22, 20266 views1 likes0 fires
18px

[!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.

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

Continue Learning

13. Constructors

Beginner
8 min

14. Encapsulation & The 'this' Keyword

Intermediate
12 min

15. Inheritance: Extending Functionality

Intermediate
14 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 Java Programming: From Zero to EnterpriseAll Categories