How to prevent method overload in Java?

You can prevent overriding methods by using the keyword final. Similarly, how to prevent overloading?

Solution

You can't do this in Java

The overload method is basically just another method

Try to look at (something) like this

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

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

However, because Java solves the overload problem by looking at the "best match" or "most specific signature", it will not work properly

This method can still be overloaded with a

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

It will be called when doing your method ("hello", "world")

BTW, why do you want to prevent overloading? Maybe there's another way to do what you want to do?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>