• Post Reply Bookmark Topic Watch Topic
  • New Topic

overloading and overriding doubt!  RSS feed

 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Should overloading happen in the same class? Can overloading happen in two different classes?
like say you have

class A {
void fun() {
}
}
class B {
void fun(int x) {
S.O.P(x);
}
}
/*** now is the above overloading************/

second doubt :

say you have

package a;

public class Xyz {
void boo() {
}
}

package B;
import a.*;

class Abc {
void boo(int b) {
S.O.P(x);
}
}
/********* now is this overloading******/

third doubt:

Overriding happens only when we talk about inherited classes is it?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by prasanna sheregar:
Overriding happens only when we talk about inherited classes is it?

Correct.
A method is being overridden if:
- the return type and parameters are exactly the same*
- the method exists in a parent class (doesn't have to be the direct parent)
- the method that is overridden is not private or static.

I've added the last line because you cannot override a private or static method - you reimplement them, hiding the method in the parent class.


* Actually, the return type can be narrower since Java 5. This is called "covariant return".


Now, overloading can only be done within the same class, so neither example is overloading.
 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if the above programs i wrote is not overloading then what is it?

But it sattisfies all rules of overloading!
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All except one: the methods are in different classes!

If "void fun()" and "void fun(int x)" were both in class A, or both in class B, or class B extended class A or vice versa, then yes, this was overloading. The same goes to "void boo()" and "void boo(int b)".

For overloading, both methods need to be available (either directly or through inheritance) in the class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!