Sobes.tech
Junior — Middle

What are the limitations of using a method with the same name in a single Java class?

sobes.tech AI

Answer from AI

In Java, a class can have multiple methods with the same name if they differ in signature — that is, in the number, types, or order of parameters. This is called method overloading.

Restrictions:

  • Methods must differ by parameters, otherwise there will be a compilation error.
  • Overloading cannot be based solely on differences in return type.
  • You cannot have two methods with the same signature, even if they differ in access modifiers.

Example:

class Example {
    void print(String s) { System.out.println(s); }
    void print(int i) { System.out.println(i); }
    // void print(String s) { } // Error: duplicate signature
}