Chapter 13 of 26

Static vs Instance Members

So far, every field we wrote belonged to an object: each Student had its own name, each Account its own balance. But some data does not belong to any single object. How many students have been admitted? What is the name of the college? What is the value of π? Storing a copy of these in every object would be wasteful and, worse, the copies could disagree.

OOP languages solve this with static members, which belong to the class itself, alongside the usual instance members, which belong to each object.

An instance member (field or method) belongs to a particular object: every object has its own copy of instance fields, and instance methods run "on" an object, available as this. A static member belongs to the class: there is exactly one copy of a static field, shared by all objects, and a static method runs without any object.

Analogy: in a classroom, each student's notebook is an instance member (everyone has one, with different contents). The whiteboard is a static member (there is one, everyone sees the same thing, and if someone writes on it, everyone sees the change).


A First Example

class Student {
    static String college = "CSLP Institute";  // one copy, shared by all students
    static int count = 0;                      // how many Student objects exist

    final int rollNo;                          // one copy per object
    final String name;

    Student(String name) {
        this.name = name;
        count++;                 // update the shared counter
        this.rollNo = count;     // give this object its own number
    }

    void introduce() {           // instance method: has 'this'
        System.out.println(rollNo + ". " + name + " studies at " + college);
    }

    static void changeCollege(String newName) {   // static method: no 'this'
        college = newName;
    }
}

public class StudentDemo {
    public static void main(String[] args) {
        System.out.println("Students so far: " + Student.count);  // no object needed

        Student a = new Student("Anil");
        Student b = new Student("Bhavna");
        a.introduce();
        b.introduce();

        Student.changeCollege("CSLP University");  // affects every student
        a.introduce();
        b.introduce();
        System.out.println("Students so far: " + Student.count);
    }
}

Output:

Students so far: 0
1. Anil studies at CSLP Institute
2. Bhavna studies at CSLP Institute
1. Anil studies at CSLP University
2. Bhavna studies at CSLP University
Students so far: 2

What this shows:

  • Student.count was readable before any object existed. Static members exist as soon as the class is loaded and initialised.

  • rollNo and name are different in a and b. college and count are the same for both, because there is only one copy.

  • One call to Student.changeCollege(...) changed what every student prints.

The memory picture

          Student class (one per program)
          ┌────────────────────────────────┐
          │ college = "CSLP University"    │   static fields:
          │ count   = 2                    │   ONE shared copy
          └────────────────────────────────┘
                 ▲                  ▲
        object a │                  │ object b
   ┌──────────────────┐     ┌──────────────────┐
   │ rollNo = 1       │     │ rollNo = 2       │  instance fields:
   │ name   = "Anil"  │     │ name   = "Bhavna"│  one copy PER object
   └──────────────────┘     └──────────────────┘

Where exactly the JVM keeps static fields is an implementation detail (in modern HotSpot they live on the heap together with the class's Class object). What matters for design is the count: one per class versus one per object.


Static vs Instance: The Rules

Point

Instance member

Static member

Belongs to

Each object

The class

Number of copies (fields)

One per object

Exactly one

Created

When the object is created with new

When the class is initialised (first real use)

Accessed as

object.member

ClassName.member

this / super available?

Yes

No

Can directly use instance members?

Yes

No: needs an object reference

Can directly use static members?

Yes

Yes

Method call resolved by

Actual object, at run time (overriding)

Declared type, at compile time (hiding)

Can be abstract?

Yes

No

The one-way rule is the key to most exam questions: instance code can use static members freely, but static code cannot use instance members without naming an object.

public class StaticError {
    int marks = 90;                  // instance field

    public static void main(String[] args) {
        System.out.println(marks);   // which object's marks?
    }
}
StaticError.java:5: error: non-static variable marks cannot be referenced from a static context
        System.out.println(marks);   // which object's marks?
                           ^
1 error

The error message is the whole explanation. A static method runs without any object, so "marks" is meaningless: whose marks? The fix is either to create an object (new StaticError().marks) or, if the value really is shared, to make the field static.

This is also why main is static: the JVM must be able to call it before any object of your class exists.


Initialisation Order: Static Blocks and Instance Blocks

Static fields can be given values in a static initializer block (static { ... }), which runs once, when the class is initialised. There is also an instance initializer block ({ ... }), which runs every time an object is created, before the rest of the constructor body.

class Config {
    static int loads;
    int id;

    static {                                   // static initializer: once per class
        System.out.println("1. static block runs (class is initialised)");
    }

    {                                          // instance initializer: once per object
        id = ++loads;
        System.out.println("2. instance block runs for object " + id);
    }

    Config() {
        System.out.println("3. constructor runs for object " + id);
    }
}

public class InitOrder {
    public static void main(String[] args) {
        System.out.println("main starts");
        new Config();
        new Config();
    }
}

Output:

main starts
1. static block runs (class is initialised)
2. instance block runs for object 1
3. constructor runs for object 1
2. instance block runs for object 2
3. constructor runs for object 2

Step by step:

  1. main starts. Config has not been touched yet, so it is not initialised.

  2. The first new Config() is the first real use of the class: the static block runs, once.

  3. For each object: the superclass constructor runs (here the implicit super() to Object), then instance field initialisers and instance blocks in source order, then the rest of the constructor body.

  4. The second object repeats step 3 only. Static blocks never run again.

When exactly does a class get initialised?

Java initialises a class lazily, on its first active use: creating an object, calling a static method, or reading/writing a static field that is not a compile-time constant. A static final primitive or String initialised with a constant expression is copied into the using code by the compiler, so reading it does not trigger initialisation:

class Limits {
    static final int MAX = 100;          // compile-time constant
    static int calls = 0;                // ordinary static field
    static { System.out.println("Limits initialised"); }
}
public class Lazy {
    public static void main(String[] args) {
        System.out.println("MAX = " + Limits.MAX);     // constant: no initialisation
        System.out.println("calls = " + Limits.calls); // first real use: initialise now
    }
}

Output:

MAX = 100
Limits initialised
calls = 0

Static Methods Are Hidden, Not Overridden

In Polymorphism and Method Overloading vs Method Overriding we saw that an overridden instance method is chosen at run time from the actual object. Static methods do not take part in this. If a subclass declares a static method with the same signature, it hides the parent's method, and the choice is made at compile time from the type of the reference.

class Parent {
    static String kind()   { return "Parent.kind (static)"; }
    String       greet()   { return "Parent.greet (instance)"; }
}

class Child extends Parent {
    static String kind()   { return "Child.kind (static)"; }    // HIDES Parent.kind
    @Override
    String       greet()   { return "Child.greet (instance)"; } // OVERRIDES Parent.greet
}

public class HidingDemo {
    public static void main(String[] args) {
        Parent p = new Child();
        System.out.println(p.greet());  // decided by the OBJECT at run time
        System.out.println(p.kind());   // decided by the REFERENCE TYPE at compile time
        System.out.println(Child.kind());
    }
}

Output:

Child.greet (instance)
Parent.kind (static)
Child.kind (static)

p refers to a Child object, yet p.kind() printed the Parent version, because p is declared as Parent. Calling a static method through an object reference is legal but misleading; javac -Xlint:static warns: "static method should be qualified by type name, Parent, instead of by an expression". Always call static methods as ClassName.method().

Also note: @Override on a static method is a compile error, and a static method cannot hide an instance method (or vice versa).


When Should Something Be Static?

Good uses

  • Constants: static final double GST_RATE = 0.18; One copy, never changes, no risk.

  • Utility functions that need no object state: Math.max(a, b), Integer.parseInt(s), Collections.sort(list). Such classes often have a private constructor so nobody instantiates them.

  • Static factory methods: List.of(1, 2, 3), LocalDate.of(2026, 11, 2). They create objects with meaningful names and can return cached or subclass instances.

  • Class-wide bookkeeping, like the object counter above.

Be careful with mutable static state

A mutable static field is essentially a global variable. Any code anywhere can change it, which brings three classic problems:

  • Hidden coupling. Two classes that both touch Settings.currentUser are connected even though neither mentions the other. (Later, in Coupling & Cohesion, this gets a name: common coupling.)

  • Hard testing. One test leaves a static value changed and the next test fails mysteriously.

  • Thread safety. All threads share the one copy. An operation like count++ is really read, add, write, and two threads can interleave those steps and lose updates.

import java.util.concurrent.atomic.AtomicInteger;

public class RaceDemo {
    static int plainCount = 0;
    static final AtomicInteger safeCount = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Runnable work = () -> {
            for (int i = 0; i < 1_000_000; i++) {
                plainCount++;                 // read, add, write: three steps
                safeCount.incrementAndGet();  // one atomic step
            }
        };
        Thread t1 = new Thread(work), t2 = new Thread(work);
        t1.start(); t2.start();
        t1.join();  t2.join();
        System.out.println("plain  = " + plainCount);
        System.out.println("atomic = " + safeCount.get());
    }
}

Output (the first number changes from run to run):

plain  = 1732035
atomic = 2000000

In this run 267,965 increments (2,000,000 − 1,732,035) were lost on the plain static int. AtomicInteger (or a synchronized block) makes each increment indivisible. Note that our Student constructor's count++ has the same weakness if students are created from several threads.

Rule of thumb: make something static when it truly has nothing to do with any individual object. If you find yourself writing many static methods that pass the same data around, that data probably wants to be an object.


Static Members in C++ and Python

C++

C++ uses the same static keyword with the same meaning inside a class. Before C++17 a non-const static data member had to be defined once outside the class (int Student::count = 0; in a .cpp file); since C++17 you can write inline static and define it in the class. Static member functions have no this pointer and are called with ClassName::function(). Because C++ has destructors, we can also count objects that are still alive:

#include <iostream>
#include <string>
#include <utility>

class Student {
    inline static int nextRoll = 1;   // C++17 inline static: defined right here
    inline static int aliveCount = 0; // one copy each, shared by the class
    int rollNo;                       // one per object
    std::string name;
public:
    explicit Student(std::string n) : rollNo(nextRoll++), name(std::move(n)) { ++aliveCount; }
    ~Student() { --aliveCount; }      // keep the count honest when objects die

    Student(const Student&) = delete;             // copies would not be counted,
    Student& operator=(const Student&) = delete;  // so forbid them in this demo

    static int alive() { return aliveCount; }     // no 'this' inside
    void show() const { std::cout << rollNo << ". " << name << '\n'; }
};

int main() {
    Student a("Anil");
    {
        Student b("Bhavna");
        b.show();
        std::cout << "alive inside block: " << Student::alive() << '\n';
    }                                             // b destroyed here
    a.show();
    std::cout << "alive after block:  " << Student::alive() << '\n';
}

Output:

2. Bhavna
alive inside block: 2
1. Anil
alive after block:  1

(The word static has other, unrelated meanings in C++, such as a local variable that keeps its value between calls, or a function visible only in one file. In this chapter we mean static class members only.)

Python

In Python, variables assigned in the class body are class attributes (shared), and attributes set on self are instance attributes. Python has @staticmethod (no self, no class) and @classmethod (receives the class as cls, often used as an alternative constructor). There are two well-known traps:

class Student:
    college = "CSLP Institute"   # class attribute: shared
    subjects = []                # class attribute: shared (and mutable!)

    def __init__(self, name):
        self.name = name         # instance attribute: per object

a = Student("Anil")
b = Student("Bhavna")

a.college = "Other College"      # creates a NEW instance attribute on a only
print(a.college, "|", b.college, "|", Student.college)

a.subjects.append("DBMS")        # mutates the ONE shared list
print(b.subjects)

class FixedStudent:
    def __init__(self, name):
        self.name = name
        self.subjects = []       # each object gets its own list

x, y = FixedStudent("X"), FixedStudent("Y")
x.subjects.append("DBMS")
print(x.subjects, y.subjects)

Output:

Other College | CSLP Institute | CSLP Institute
['DBMS']
['DBMS'] []
  • Assigning a.college = ... does not change the class attribute. It creates a new instance attribute on a that shadows it. To change the shared value, assign to Student.college.

  • Mutating a mutable class attribute (a.subjects.append(...)) changes the one shared list for everybody. Per-object lists must be created in __init__.


Common Mistakes

  • Using an instance field inside main or another static method without an object: "non-static variable cannot be referenced from a static context".

  • Expecting polymorphism from static methods. They are hidden, not overridden; the reference type decides.

  • Calling static members through objects (a.count). It works but suggests the value is per object. Write Student.count.

  • Making things static "so I don't need to create an object". This turns OOP code back into procedural code with global variables.

  • Assuming static means constant. static means "one per class"; final means "cannot be reassigned". A constant is usually both.

  • Forgetting thread safety for mutable static fields shared by many threads.


Interview and GATE-Style Questions

Q1. Why can a static method not use this?

A static method is called on the class, not on an object, so there is no current object for this to refer to. For the same reason it cannot directly access instance fields or call instance methods.

Q2. Can we override a static method in Java?

No. A subclass static method with the same signature hides the parent's method. Which one runs depends on the compile-time type of the reference (or the class name used), not the run-time object. @Override on it is a compile error.

Q3. Three objects of class C are created. C has one static block, one instance block and a constructor that each print a line. How many lines are printed?

1 (static block, once) + 3 × 2 (instance block and constructor per object) = 7 lines.

Q4. Can a static method access a static field? Can an instance method access a static field?

Yes to both. Only the direction "static code → instance member" needs an explicit object reference.

Q5. Why is main static?

So that the JVM can call it as the program's entry point without first creating an object of the class (which would also raise the question of which constructor to use).

Q6. Two threads each run Counter.count++ 1000 times on a static int starting at 0. Is the final value always 2000?

No. count++ is not atomic (read, add, write), so updates can be lost and the result can be anything from far less than 2000 up to 2000. Use AtomicInteger or synchronisation.

Q7. In Python, after a.college = "X", what does Student.college print?

The original class value. The assignment created an instance attribute on a only, which shadows the class attribute for a.


Summary

  • Instance members belong to objects: one copy of each field per object; methods run with this.

  • Static members belong to the class: one shared copy; methods run with no object, so no this.

  • Static code cannot touch instance members without an object reference; instance code can use static members freely.

  • Static blocks run once when the class is first actively used; instance blocks run for every object, before the constructor body.

  • Static methods are hidden, not overridden: the reference type decides.

  • Use static for constants, stateless utilities, factory methods and class-wide data. Be wary of mutable static state: it is global, hard to test and shared across threads.

  • C++: same idea, inline static since C++17. Python: class attributes vs instance attributes, watch out for shadowing and shared mutable defaults.

Ask "does this belong to one object, or to the idea of the class?" The answer tells you instance or static.