Overloaded and redefined in Java

I know how to overload a method and how to override a method. But is it possible to overload and override the method at the same time? If yes, please give an example.

+6
source share
3 answers

Overloading and overriding are optional things, overloading means the same method name, but different parameters, and overriding means the same method name in a subclass with the same parameters. Thus, it is impossible to overload and redefine what is happening at the same time, since overloading involves different parameters.

Examples:

class A { public void doSth() { /// } } class B extends A { public void doSth() { /* method overriden */ } public void doSth(String b) { /* method overloaded */ } } 

Hurrah!

+13
source

overloading and overloading are just abstractions. Overloading simply means that the compiler uses this name in combination with the types and number of parameters to address the function to call. In fact, method overloading is no different from naming it something else, because the key used by the compiler to search for a function is a combination of a name and a list of parameters.

Overriding is the same principle, except that the compiler can access the overriden function with the super keyword.

So, can you override the overloaded function? Yes, since the overloaded method is a completely different method in the eyes of the compiler.

+5
source

It depends on what you mean. A method can be an override for an overloaded method in a superclass. And you can overload a method that you override with another method at the same time.

However, you cannot have one method, which is both a new overload and an override. In order for the method to be overridden, another method with the same signature must still exist in the superclass ... and this means that this method cannot be a new override.

+1
source

Source: https://habr.com/ru/post/915584/


All Articles