Java.Core.Can a Non-Static Method Overload a Static Method?

Can a Non-Static Method Overload a Static Method?

Yes! A non-static method can overload a static method in the same class, as long as they have different parameter lists.

Key Points:

Overloading is based on method signatures (same method name but different parameters).
✅ Since overloading is resolved at compile-time, it does not matter whether the method is static or non-static.
✅ Java allows both static and non-static methods to coexist with the same name in a class, as long as they have different parameters.


Example: Non-Static Method Overloading a Static Method

class OverloadingExample {
    // Static method
    static void display(String message) {
        System.out.println("Static method: " + message);
    }

    // Non-static method with different parameters (Overloading)
    void display(int number) {
        System.out.println("Non-static method: " + number);
    }

    public static void main(String[] args) {
        // Calling the static method
        OverloadingExample.display("Hello!");

        // Calling the non-static method requires an instance
        OverloadingExample obj = new OverloadingExample();
        obj.display(42);
    }
}

Output:

Static method: Hello!
Non-static method: 42

Explanation:

  • The static method display(String message) is resolved at compile-time.
  • The non-static method display(int number) is also resolved at compile-time.
  • Both methods have different parameter lists, so method overloading is valid.

Can a Non-Static Method Override a Static Method?

No! A non-static method cannot override a static method because overriding is based on runtime polymorphism, and static methods do not participate in runtime polymorphism.


Final Answer:

  • Overloading: A non-static method can overload a static method (if it has a different parameter list).
  • Overriding: A non-static method cannot override a static method.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.