Java QA:What is Overriding?

thanassis | Java Questions And Answers | Wednesday, January 3rd, 2007

We can think of overriding as redefining. When we want to redefine an inherited behaviour in a more specialised way, we must provide implementation with the exact method signature as the inherited method (that we want to redefine).

For example:

If I define class A:
class A{
void m(){
We can be making objects from A like this:
A a = new A;
And we can call its method m like this:

If we also define class B as a child of A like this:
class B extends A {
Then we know it inherits method m from its parent, class A

So we can do this:
B b = new B();
The above works because m is inherited.

Now , if we want to redefine B’s method m, then we must “override” it:

class B extends A{
//this is an overriden method
void m() {

Finally when we have:
B b = new B();

B’s method m will be called as we would expect -that is, the overridden method and not the inherited-.

But lets consider the following:
A a = new B();

Which method is going to get called on the above snippet?
A’s m() or B’s m()?

Knowing the answer is the first step towards understanding java’s polymorphism. It’s B’s method m() that will be called as polymorphism will work in this case. Although we referenced a B object to the reference of its parent (A), java can still find the most specialised methods of object a when asked.

No Comments

No comments yet.

Leave a comment

RSS feed for comments on this post. TrackBack URI