billu billu - 1 year ago 45
Java Question

How to prevent a method from overloading in Java?

Overriding a method can be prevented by using the keyword

, likewise how to prevent overloading?

Answer Source

You can't do that in Java.

An overloaded method is basically just another method.

An attempt could look (something) like this

void yourMethod(String arg) { /* ... */ }

void yourMethod(String arg, Object... prevent) {
    throw new IllegalArgumentException();

but it won't work since Java resolves overloading by looking at the "best match" or "most specific signature".

The method could still be overloaded with a

void yourMethod(String arg, String arg2) { /* ... */ }

which would be called when doing yourMethod("hello", "world").

Btw, why would you want to prevent overloading? Perhaps there is another way of doing what you want?