Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a method from overloading in Java?

Overriding a method can be prevented by using the keyword final, likewise how to prevent overloading?

like image 472
billu Avatar asked Jun 07 '10 07:06

billu


People also ask

How do we prevent a method from being overriding?

Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated. An abstract class can contain abstract methods—methods that are declared but not implemented.

Can we prevent overriding a method without using the final modifier?

Remember, though syntactically you can use private, static and final modifier to prevent method overriding, but you should always use final modifier to prevent overriding. final is best way to say a method is complete and can't be overridden.


2 Answers

You can't. Because it's almost pointless.

If you want to overload the method handle(..) but you are disallowed to, you'd create doHandle(..) instead.

Which overloaded method is used is determined at compile time (in contrast to overridden methods, which are determined at runtime). So the point of overloading is sharing a common name for common operations. Disallowing that is a matter of code-style, rather than anything else.

like image 99
Bozho Avatar answered Nov 15 '22 17:11

Bozho


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?

like image 36
aioobe Avatar answered Nov 15 '22 17:11

aioobe