File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloaded method , a simple question...

 
Prashanth Lingala
Ranch Hand
Posts: 66
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


My Question:
You can declare an overloaded method in a subclass, as i have done here...
but what is the point if i cant use it using a superclass reference...
please explain it...

Regards
Prashanth Lingala
 
David Harkness
Ranch Hand
Posts: 1646
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only thing that overloaded methods have in common is their name. You have simply added a new method to your subclass that doesn't exist in the superclass. Since the method that takes a String parameter is defined only for the Dog class, you have to have the correct reference type (Dog) to call it. This would be no different from adding a Dog.bark() method: you couldn't doBy the way, why AnimalSound rather than Animal? Is a Dog a more specific type of AnimalSound?

In contrast, overriding a method is adding a method with the exact same signature (return type and parameter types and order). This way, when you call the method, the runtime type of the object determines which method is executed.
 
Georgy Bolyuba
Ranch Hand
Posts: 162
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Using of a subclass by using it's superclass reference is needed when you
know _what_ will subclass do, but don't know _how_. In your example:
You know that all animals scream (AnimalSound.scream()), but you don't know how. You also know, that dogs are animals, so they should scream. You can do something like this:


Methods public void scream() and public void scream(String s) are not related. I mean, they related as any other couple of methods. (public void A() public void B(String s)).

I think, you can do something like this:


Hope it help.
 
Prashanth Lingala
Ranch Hand
Posts: 66
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I get it... Thanks...
And yes Dog extending Animal sounds better...
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic