Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Needs explanation

 
Venkat Ramsimha
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can a method that�s overloaded but not overridden by a subclass.
It�s perfectly legal to do the following:
public class Foo {
void doStuff() { }
}
class Bar extends Foo {
void doStuff(String s) { }
}

hi all,
how can the above is possible?can anybody provide the explanation for the above?


thanks
venkat
 
S.L.Narayanan
Ranch Hand
Posts: 431
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not?

I could not understand why you got this doubt first of all. Leave that. Lets come to the topic.


public class Foo {
void doStuff() { }
}
class Bar extends Foo {
void doStuff(String s) { }
}


Above is the code given by you.
If you consider the following code


Class Bar
{
void doStuff() { }
void doStuff(String s) { }
}


what will you say?...This is a piece of code with method overloading..right?...Similarly when you extend a class with some methods that are visible to the child class you can call them with the child object also. That means they are almost in Child class except for the fact that they are derived methods. Now if u add one more method in the child class with the same method name as the one got from parent but with different set of parameters, how will u call it?...Thats what you have done in your code.

Method overriding completely replaces the method from the parent. But here you can still access the method from your parent (no-arg) as well as your own method with the same name(1-arg). So this is method overloading not overriding.

Clear?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic