my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Overloaded method , a simple question... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overloaded method , a simple question..." Watch "Overloaded method , a simple question..." New topic
Author

Overloaded method , a simple question...

Prashanth Lingala
Ranch Hand

Joined: Nov 13, 2004
Posts: 66


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


Have A Nice Day !!!
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
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

Joined: Feb 18, 2005
Posts: 162
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.


SCJP 1.4 (100%) Done.<br />SCJD (URLyBird 1.2.3 Started)
Prashanth Lingala
Ranch Hand

Joined: Nov 13, 2004
Posts: 66
I get it... Thanks...
And yes Dog extending Animal sounds better...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overloaded method , a simple question...
 
Similar Threads
SCJP Brainteaser (11)
Problem with System.out.print
begin execution of a thread -- start or run?
polymorphism
basic object question