Method Overriding
- What is Polymorphism?
- Method Overriding
- How to call overridden function from the child class
- Rules of Method overriding
The overriding method can only be written in Subclass, not in same class.
If a method cannot be inherited then it cannot be overridden.
-
The argument list and the return type should be exactly the same as that of the overridden method.
Constructors cannot be overridden (cannot be inherited in a subclass).
-
A method declared final or static cannot be overridden.
- Conclusion
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.
Like we specified in the previous chapter: Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.
Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So, the same person possesses different behavior in different situations. This is called polymorphism.
The method overriding is a technique to achieve polymorphism.
Method overriding is a feature that allows us to have a same function in child class which is already present in the parent class. A child class inherits the data members and member functions of parent class, but when you want to override a functionality in the child class then you can use function overriding. It is like creating a new version of an old function, in the child class.
Example :
class Animal {
void talk() {
print("I am an animal");
}
}
class Bird extends Animal {
void talk() {
print("I am a Bird");
}
}
class Fish extends Animal {
void talk() {
print("I am a Fish");
}
}
void main() {
var a1 = Animal(), a2 = Bird(), a3 = Fish();
a1.talk();
a2.talk();
a3.talk();
}
I am a Bird
I am a Fish
We can use the super keyword in the subclass to invoke the overridden method without creating an object from the parent class.
Example :
class Animal {
void talk() {
print("I am an animal");
}
}
class Bird extends Animal {
void talk() {
super.talk();
print("I am a Bird");
}
}
class Fish extends Animal {
void talk() {
super.talk();
print("I am a Fish");
}
}
void main() {
var a1 = Animal(), a2 = Bird(), a3 = Fish();
a1.talk();
print("-----");
a2.talk();
print("-----");
a3.talk();
}
-----
I am an animal
I am a Bird
-----
I am an animal
I am a Fish
Method Overriding is the ability of a subclass to override a method inherited from a superclass whose behavior is "close enough" and then modify behavior as needed.
Also, it able the child class to give its own implementation to a method which is already provided by the parent class. In this case the method in parent class is called overridden method and the method in child class is called overriding method.