my dog learned polymorphism
The moose likes Java in General and the fly likes Method Overriding. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Method Overriding." Watch "Method Overriding." New topic

Method Overriding.

Nilesh Srivastava
Ranch Hand

Joined: Aug 29, 2003
Posts: 70
Hi All,
Very basic thing to ask...
Why do we use method overriding..(Purpose of Method Overriding)
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

I'm still pretty new myself, but here's my spin on it.
assume you have a class A with several methods. now, you use inheritance, and create a sub-class called B. B has everyting A has - member variables and methods.
Now you can add new stuff to B, and life is good.
But what if you want B to do something similar to what A does, but just a little different? It will take the same input parameters, and called the same...

Why would you do this??? because you can.
Seriously, it does come in handy. I believe the grand-daddy Object class has a method called "toString()". this garantees that you can call toString() on ANYTHING. It's not always real useful what this puts out, but hey, at least it's there, and your program won't crash.
Quite often, you want to have your object put out usefull data when you call ITS toString(). so, you OVERRIDE the Object.toString() with your own. that way, you can get helpful data.
hope this helps...

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Nilesh Srivastava
Ranch Hand

Joined: Aug 29, 2003
Posts: 70
Hi Fred,
Thanks for replying me.
Well, I still have some doubts poping r they for u..
Ok..ur Grand Daddy Object class has toString() method which u overriode and used it accordingly.thats fine..
But, If I didnt override the toString() then any call to that function will call toString() of Grand- daddy.
If I have to use the method in my class then I would better like to write it on my own and use it accordingly.Why should I override any existing method of Grand daddy.
Thanks and regards,
Tom Blough
Ranch Hand

Joined: Jul 31, 2003
Posts: 263
When you pass an object to System.out.print(), it automatically calls the objects toString() method. The default toString method inherited from Object, just prints out the objects type and its location in memory - not something very useful.
When we create a class of our own, one of the first things we should do is override the toString method inherited from Object to give us useful information when the object is printed. Normally we override toString to provide us with information about the state (the values of our object's instance data) of our object.
Overriding methods comes into play when we begin to use the power of polymorphism. A classic example of this is a superclass called GeometricObject. A geometric object will have data about the number of sides. We also know that a geometric object will have certain properties we can compute such as it's area and it's circumference. The problem is that we don't really know how to calculate these values without knowing exactly what kind of geometric object we have.
So, what we do is subclass GoemetricObject. We create a class called Square that inherits from GeometricObject and overides the parents area() method to return something like side*side. We do this instead of creating a method like squareArea() in the Sqaure class. We can also create a Triangel class that inherits from GeometricObject. Triangle would override area() to return 0.5*base*height.
Now, if we have a collection of GeometricObjects (an array, list, hash, etc) we can iterate through the collection. If we treat each object in the collection as a GeometricObject (the parent class) instead of it's specific type (like Square, Triangle, etc), we can still call the area() method (since we defined it in GeometricObject), but amazingly what will happen is the area() method of the SPECIFIC object will be called and the correct area will be printed!
This is exactly what happens with the toSring() method. You can pass any object to println and it will call THAT object's toString method even though println is calling Object.toString().

Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

Again, this is just another beginners attempt to explain... what follows is a pretty standard example.
say i have a parent class Pet, with a speak() method. all this does is prints "This pet can't talk". now, i create three sub-classes, dog, cat, and bird, that are all children of Pet. if i do nothing, each will inherit the method as is.
now, for each, i override it with it's version of the method, so the dog will "bark", the cat will "meow", and the bird will "chirp".
yes, i could write a new method for each, called "dogSpeak", "catSpeak" and "birdSpeak", and it would accomplish the same thing.
so far so good?
now, i want all my animals implemented, and then i want them all to speak to me. It would be nice if i could put them all in an array. but an array only allows one type of object to go into it. i don't want a Dog array, a Cat array, and a bird array. this is very cumbersome.
so, i can make a Pet array. every Dog is a Pet. every Cat is a Pet. so i can put them all into the same array. i can then write a for loop that goes through each pet to get it to speak. Each time i pull something out of the array, all i can be sure of is that it is a Pet. i don't know what KIND of pet it is.
if i do it your way, i have to set up
if it's a dog
Dog tempDog = (Dog)array[i]
else if it's a cat
Cat tempCat = (Cat)array[i]
then, if i implement a Fish, Ferret, Snake, etc. i have to keep tweaking this.
but if all i do is override the existing method, life is much easier. as i itereate through the array, i can just say
we are garunteed to have a speak method (if nothing else, i have the inherited one). then, if it's a dog, JAVA KNOWS ITS A DOG, AND WILL CALL THE SPEAK METHOD FOR A DOG. same for Cat and Bird.
that's the cool part. JAVA KNOWS.
now, when i implement the new Ferret class, I DON'T HAVE TO DO ANYTHING to the stuff where i have them speak. i can just put in a Ferret, since it's a Pet. the same code will work.
when i first heard this, i though, "well that's nice, but what's the big deal about adding another case?"...
eventually, you will be working on large project. i'm talking literally MILLIONS of lines of code. you'll never even SEE most of it. and some of it might be written by people thousands of miles away. there might be HUNDREDS of places where a Pet array is iterated over. do you really want to have to add your case to all 100, every time you create a new class? what if you miss one or two cases, and your product gets shipped to the customers??? (trust me, it's happened).
This is pretty complicated stuff. I came to java with some C++ experience, which uses a lot of the same concepts (in fact, most Object Oriented languages do). It really is cool, once you get it.
Hope this isn't too long, or complicated. feel free to ask more questions, and mouse around some of the other places. i've found the examples and stories on this site VERY helpful...
Greg Donahue

Joined: Oct 07, 2003
Posts: 24
It seems to me that method overriding is done for a number of reasons. The first is convenience. If you're in the process of writing a class, and you decide that you'll include a method which returns a String representation of the class's instances (objects), you are entitled to call that method whatever you want. You don't have to call it toString(). You could call it getString(), or makeString(), or whatever. But Java programmers have, by and large, accepted that such methods are called toString() methods.
This is especially useful when someone, somewhere down the line needs to figure out how your class works. Suppose this guy (sorry about the gender cast; I do it for clarity's sake) has created an object of your zillion line class for use in his own program. Suppose that he needs to check the data the object encapsulates to make sure he's using it correctly. Well, it would be great if the object could call a toString() method to display its internal data (its data fields). Of course, if you've named your toString() method something else, he'll have to dig around in the docs/comments you left him (which is never fun when all you want to do is get toString() output)! So writing toString() methods is just a courtesy programmers extend to one another.
Another reason we use method overriding is for abstraction. To use the animal example given above, you could write new methods for each animal. You could write bark() for the Dog class and meow() for the Cat class and Neigh() for the Horse class...but after you have created enough animals, it would be difficult to keep track of all these speak() derivatives. It's much simpler to have a single speak() method in the superclass, and then override it in a subclass if you have to. This allows the subclasses to be general (using the superclass methods) or specific (overriding those methods) as the situation requires.
Hope that helps!

vi veri veniversum vivus vici
I agree. Here's the link:
subject: Method Overriding.
It's not a secret anymore!