Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Needs explanation

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 431
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic