OOPs4Humans

Static Keyword

Shared by everyone.

The Static Keyword

Analogy: community

Static is like a Town Clock.

  • Everyone in the town looks at the same clock.
  • If you change the time on the clock, it changes for everyone.

Non-Static is like a Wristwatch.

  • Everyone has their own watch.
  • Changing your watch doesn't affect anyone else.

The Global Scoreboard

Imagine a game where all players contribute to a Team Score.

  • If score is static, all players share the same score variable.
  • If score is not static, each player has their own private score.

Global Scoreboard (Static vs Non-Static)

Variable Type:
Shared by ALL instances
Static Memory
0

Player 1

(Reads Static)0

Player 2

(Reads Static)0

Player 3

(Reads Static)0

The Code

Use the static keyword to make a variable shared.

Java Example
Switch language in Navbar
class Player {
    static int teamScore = 0; // Shared!
    int personalScore = 0;    // Not Shared
}

Player p1 = new Player();
Player p2 = new Player();

p1.teamScore += 10;
// p2.teamScore is ALSO 10 now!

Advanced Concepts

The Final Keyword

While static means "shared", final means "unchangeable".

  • Final Variable: A constant. Once assigned, it cannot be changed.
  • Final Method: Cannot be overridden by a subclass.
  • Final Class: Cannot be inherited from.
Java Example
Switch language in Navbar
class MathConstants {
    // static final = Global Constant
    static final double PI = 3.14159;
}

// MathConstants.PI = 3.14; // Error!