File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Why to override?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why to override??" Watch "Why to override??" New topic

Why to override??

Anu satya
Ranch Hand

Joined: Mar 17, 2005
Posts: 146
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!!

With Regards,
Mike Vella Zarb

Joined: Dec 28, 2009
Posts: 21
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
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:
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

It is a mistake to think that you can solve any major problem with just potatoes.
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
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.

JDBCSupport - An easy to use, light-weight JDBC framework -
Arvind Porlekar
Ranch Hand

Joined: Dec 31, 2008
Posts: 38
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 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.

I agree. Here's the link:
subject: Why to override??
It's not a secret anymore!