Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why to override??

 
Anu satya
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a very basic doubt.

Why to override a super class's method in its subclass? is it not similar to writing a same method in subclass also?? what is the use of overriding? If the answer is runtime polymorphism, how does it really work? is it almost like duplicating the code in super class right?

so, why to override?

Please help me!!
 
Mike Vella Zarb
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
You override to make a method more specific. Let's say that you have class Animal extended/inherited by class Dog.
In class Animal there is a method
eat(){
System.out.println("Animal Eating");
}

Since Dog inherits Animal eat() is available to it also - but we can override the method to make it more specific:
eat(){
System.out.println("Dog Eating");
}
This means that if we call the method eat() from an Animal instance, we get Animal Eating, and if we call the method eat() from a Dog instance, we get Dog Eating
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can imagine it better if you use the word 'redefine'. Overriding is to implement an alternative behavior or just an alternative way to achieve the same behavior compared to the behavior inherited from the superclass.

The question about runtime Polymorphism: Check this code


At runtime, the JVM will invoke the dog's and cat's version of walk, as this is the specific type at runtime. And that is what runtime Polymorphism does for you.
 
Arvind Porlekar
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Override means you are redefining the method with more specific way.
suppose the scenario where the method is already there in API Or in other class,and you want to add more features into that method ..how that can be possible..?
Override is the option, because you can not modify the API Or other Class for your specific requirement.

I don't think so there is any duplicate code because you are adding new features into override method.


-Arvind
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic