Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded and overridden in Java

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

like image 225
Weitao Wang Avatar asked May 13 '12 01:05

Weitao Wang


2 Answers

overloading and overloading are just abstractions. Overloading just means the compiler uses the name in conjunction with the types and number of parameters for addressing what function to call. In reality overloading a method is no different than naming it something different because the key the compiler uses to look up the function is a combination of name and parameter list.

Overriding is kind of the same principle except the compiler can address the overriden function with the super keyword.

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

like image 126
5 revs Avatar answered Oct 05 '22 00:10

5 revs


Overloading and overriding are complementary things, overloading means the same method name but different parameters, and overriding means the same method name in a subclass with the same parameters. So its not possible for overloading and overriding to happen at the same time because overloading implies different parameters.

Examples:

class A {
    public void doSth() { /// }
}

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

    public void doSth(String b) { /* method overloaded */ }

}

Cheers!

like image 32
Juan Alberto López Cavallotti Avatar answered Oct 04 '22 22:10

Juan Alberto López Cavallotti