⏱ 7 min read

Static Methods in Java

Complete guide to static methods, method hiding, overriding behavior, and design considerations.


Table of Contents


1. Static Methods in Java

1.1 What Is a Static Method?

A static method belongs to the class, not to an individual object.

Characteristics:

  • Called using class name
  • Loaded once when the class is loaded
  • Does not depend on object state
StaticMethod.getOddSum(10);

πŸ“Œ Key idea: static methods operate at the class level, not object level.


1.2 How Static Methods Are Declared

public static int getBurgerPrice() {
    return burgerPrice;
}
  • static keyword makes the method class-level
  • No object is required to call it

1.3 Static Methods and Instance Variables

// ❌ Not Allowed
price++;

Reason:

  • price is an instance variable
  • Static methods do not know which object to use

πŸ“Œ Rule: static methods cannot directly access non-static members.


1.4 Static Methods and Static Variables

// βœ… Allowed
burgerPrice += 10;

Reason:

  • Static variables are also class-level
  • Shared across all objects

πŸ“Œ Mental model: static talks only to static.


1.5 Calling Non-Static Methods from Static Methods

// ❌ Direct call not allowed
printSum(sum);

// βœ… Correct approach
StaticMethod obj = new StaticMethod();
obj.printSum(sum);

πŸ“Œ Why? Non-static methods need an object context.


1.6 How Static Methods Should Be Called

// ❌ Allowed but discouraged
obj.getOddSum(11);

// βœ… Recommended
StaticMethod.getOddSum(11);

πŸ“Œ Best practice: always call static methods using the class name.


1.7 Static Methods and Polymorphism

  • Static methods cannot be overridden
  • They are resolved at compile time
  • Method call depends on reference type, not object type

πŸ“Œ This is called method hiding, not overriding.


1.8 Common Use Cases of Static Methods

  • Utility/helper methods
  • Mathematical calculations
  • Factory methods
  • Constants-related operations
  • Entry point: main() method

1.9 Static vs Instance Methods (Quick Comparison)

Feature Static Method Instance Method
Belongs to Class Object
Access instance data ❌ βœ…
Requires object ❌ βœ…
Can be overridden ❌ βœ…
Polymorphism ❌ βœ…

1.10 Final Carry-Forward Points

  • Static methods belong to the class
  • Cannot directly access instance members
  • Can access static variables and methods
  • Should be called using class name
  • Do not support runtime polymorphism

2. Static Methods and Overriding in Java

2.1 Can Static Methods Be Overridden?

No. Static methods cannot be overridden in Java.

  • Static methods belong to the class, not to objects.
  • Overriding requires runtime polymorphism, which static methods do not support.

2.2 Why @Override Is Not Allowed on Static Methods

Parent class

class Person {
    public static void profession() {
        System.out.println("I'm in Person Class.");
    }
}

Child class (with @Override)

class Doctor extends Person {

    @Override
    public static void profession() {
        System.out.println("Doctor profession");
    }
}

Result: ❌ Compile-time error

Reason:

  • @Override means: this method must override a parent method.
  • Static methods do not participate in overriding.
  • Hence, the compiler rejects it.

πŸ“Œ Rule: @Override can only be used with instance methods.


2.3 Why Code Works After Removing @Override

class Doctor extends Person {

    public static void profession() {
        System.out.println("Doctor profession");
    }
}

What is happening here?

  • This is not overriding; it is method hiding.
  • Both methods exist separately.

πŸ“Œ Key Concept: static methods with the same signature in parent and child cause method hiding, not overriding.


2.4 What Is Method Hiding?

Definition

  • Method hiding occurs when a child class defines a static method with the same signature as a static method in the parent class.
  • Only applies to static methods.
  • Resolved at compile time.
  • Depends on class name, not object.

2.5 Behavior at Runtime (Observation Explained)

Test code

Doctor.profession();
Person.profession();

Output

Doctor profession
I'm in Person Class.

Why this happens

  • Static methods are called using the class name.
  • JVM does not use dynamic dispatch for static methods.

πŸ“Œ Important: static method calls are bound at compile time.


2.6 Static vs Instance Method Resolution

Instance method (overriding)

Person p = new Doctor();
p.profession();   // calls Doctor's method

βœ” Runtime polymorphism; object type matters.

Static method (hiding)

Person.profession();
Doctor.profession();

βœ” Compile-time binding; class name matters. ❌ No polymorphism.


2.7 Why Static Methods Cannot Be Overridden

Reason Explanation
No object context Static methods are class-level
Compile-time binding Decision made before runtime
No dynamic dispatch JVM does not choose at runtime

πŸ“Œ One-liner: Overriding needs runtime polymorphism; static methods don’t have it.


2.8 Common Interview Trap

Person p = new Doctor();
p.profession();   // calls Person.profession()

Explanation

  • Method is static.
  • Reference type (Person) decides the call.
  • Object type (Doctor) is ignored.

2.9 Static vs Instance Methods (Quick Comparison)

Feature Instance Method Static Method
Can be overridden βœ… ❌
Polymorphism Runtime ❌
Binding time Runtime Compile time
Uses @Override βœ… ❌
Belongs to Object Class

2.10 Final Carry-Forward Points

  • Static methods cannot be overridden.
  • Using @Override on static methods β†’ compile error.
  • Same static method in child = method hiding.
  • Static calls depend on class name.
  • No runtime polymorphism for static methods.

βœ… Mental Model:

  • Instance methods β†’ object behavior.
  • Static methods β†’ class behavior.

πŸ“˜ Instance Methods vs Static Methods

Aspect Instance Methods Static Methods
Belong to Object Class
Object required to call βœ… Yes ❌ No
Accessed using Object reference Class name
Access instance variables βœ… Yes ❌ No
Access static variables βœ… Yes βœ… Yes
Polymorphism βœ… Supported ❌ Not supported
Method resolution Runtime (dynamic binding) Compile time (static binding)
Overriding βœ… Allowed ❌ Not allowed
Method hiding ❌ Not applicable βœ… Possible
Use of @Override βœ… Valid ❌ Compile-time error
Depends on Object type Reference / class name
Inheritance behavior Inherited and overridden Inherited but hidden
Uses this keyword βœ… Yes ❌ No
Typical use case Object-specific behavior Utility / class-level behavior
Example obj.calculate() Math.max()
Memory One copy per object One copy per class
Can be abstract βœ… Yes ❌ No
Can be final βœ… Yes βœ… Yes

3. Static Method Definition and Design Considerations

This example highlights how static and instance methods should be designed, and where developers must be careful.

3.1 Valid Static Method (Best Practice)

public static int sum(int a, int b) {
    return a + b;
}

Why this is good design:

  • Uses only method parameters
  • Does not depend on object state
  • Produces predictable results
  • Easy to test and reuse

πŸ“Œ Rule: A static method should ideally be stateless.


3.2 Valid Instance Method Using Static Variable

public int sum2(int a, int b) {
    carPrice += a + b;
    return a + b;
}

Why this is acceptable:

  • Instance methods have access to:
    • Instance variables
    • Static variables
  • Object context is available
  • Behavior is explicit

πŸ“Œ Key point: Instance methods can safely modify static variables, but such design must be intentional.


3.3 Static Method Modifying Static Variable (⚠️ Caution)

public static int sum3(int a, int b) {
    carPrice += a + b;
    return a + b;
}

Why this is risky:

  • Static variable is shared across all objects
  • Any call can change global state
  • Order of calls affects result
  • Harder to debug and reason about

πŸ“Œ Important: Static methods modifying static variables introduce hidden side effects.


3.4 Key Design Difference Highlighted

Method Uses Object State Modifies Global State Risk Level
sum() ❌ ❌ βœ… Safe
sum2() βœ… βœ… ⚠️ Moderate
sum3() ❌ βœ… ❌ High

3.5 Why This Matters in Real Projects

Static methods are often treated as utility methods.

Utility methods are expected to be:

  • Stateless
  • Predictable
  • Thread-safe

Modifying static variables breaks these expectations.

πŸ“Œ Interview Insight: Static methods should not change shared state unless explicitly required.


3.6 Best Practices to Remember

  • Prefer pure static methods (no shared state)
  • Use instance methods when behavior depends on object data
  • Avoid static methods that mutate static variables
  • Treat static variables as global state

3.7 One-Line Mental Model

Static methods should compute, not mutate.

Instance methods represent behavior tied to state.


← Back to Basics β˜• Java Hub