English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

One of the fundamental concepts of object oriented programming.

2006-06-10 14:03:25 · 4 answers · asked by tjhauck2001 2 in Computers & Internet Programming & Design

4 answers

Think of overriding as redefining.
When you want to redefine an inherited behaviour in a more specialised way, you must provide implementation with the exact method signature as the inherited method (that you want to redefine).
As an example (in java):

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

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

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

Now , if I want to redefine B's method m, then I must "override" it like this:

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

Then when I have:
B b = new B();
b.m();

B's method m will be called as you would expect -that is, the overridden method and not the inherited-.
This should answer your question as to what we mean with the term "overriding".

But do consider the following:
A a = new B();
a.m();

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 if asked.
I wont go into explaining polymorphism, but to fully understand the reasons behing overriding you must see it in the context of the rest of the object oriented characteristics and most importantly that of polymorphism.

2006-06-10 22:25:07 · answer #1 · answered by thanassis 4 · 1 0

What Is Method Overriding

2016-11-02 01:20:46 · answer #2 · answered by ? 4 · 0 0

Method overriding is "replacing" a method from a parent class. In OOP, inheritance allows child classes to inherit methods and attributes from the parent class. But sometimes you want to override a method to better define it for the subclass. Don't confuse this with method overloading, which is using the same method name as another method but with different arguments.

2006-06-10 14:42:20 · answer #3 · answered by LostMonkey 2 · 0 0

Method overriding deals with inheritance.

Say a base class defines and implements a method, but it leaves the method abstract or virtual.

Any derived class may use the base class' implementation, or provide its own replacement. When the derived class replaces the base class' implementation, it has overridden it.

2006-06-10 14:27:25 · answer #4 · answered by MarleyTheCat 3 · 0 0

fedest.com, questions and answers