Function overriding in programming
Last Updated :
29 May, 2024
Function Overriding is a fundamental principle in object-oriented programming wherein the subclass implements a specific method that has been declared in the superclass. This concept would enable the method calls to be polymorphic where the same method call may behave differently depending on the object which initiated the method call. In this article, we will discuss the basics of Function Overriding along with its implementation in different languages.
What is Function overriding?
Function overriding is when a function in the base class is redefined in the derived class to provide a different implementation of the function for the derived class. The function in the derived class has the same function signature as the function in the base class (same name, same return type, same arguments). Function overriding provides a way to implement polymorphism.
Function overriding in C++:
C++ provides function overriding with the use of virtual functions in inheritance. In case the function in the base class is declared as virtual and is overridden in the derived class, the derived class’s implementation will be called if the method is called through the reference or pointer of the base class.
Below is the implementation of function overriding in C++:
C++
#include <iostream>
using namespace std;
class Animal {
public:
virtual void makeSound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Dog barks" << endl;
}
};
int main() {
Animal* animal = new Dog(); // Upcasting
animal->makeSound(); // Output: Dog barks
delete animal;
return 0;
}
Explanation: In C++, function overriding is achieved using virtual functions. The Animal class declares the makeSound() function as virtual, and the Dog class overrides it. When makeSound() is called on a Dog object, it prints "Dog barks".
Function overriding in Java:
Method overriding is a core of Java wherein a subclass has the ability to override or provide its own version of a method that is in the superclass. Sometimes in Java the @Override annotation can be used which ensures that the particular method is intended to override the specific method of the superclass.
Below is the implementation of function overriding in Java:
Java
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
animal.makeSound(); // Output: Dog barks
}
}
Explanation: In this Java example, the Animal class has a method makeSound(). The Dog class inherits from Animal and overrides the makeSound() method with its own implementation. When makeSound() is called on a Dog object, it prints "Dog barks".
Function overriding in Python:
Function overriding comes to Python quite easily and it is also supported due to Python being a dynamic language. Inheritance makes it possible for subclasses to override methods from a superclass by mere demonstration. It is also possible to define classes in Python that feature an inheritance mechanism where subclasses can inherit and/or override methods of a parent class.
Below is the implementation of function overriding in Python:
Python
class Animal:
def make_sound(self):
print("Animal makes a sound")
class Dog(Animal):
def make_sound(self):
print("Dog barks")
animal = Dog()
animal.make_sound() # Output: Dog barks
Explanation: In Python, function overriding is straightforward. The Dog class inherits from Animal and provides its own implementation of the make_sound() method. When make_sound() is called on a Dog object, it prints "Dog barks".
Function overriding in C#:
Overriding can be achieved in C# by the using the override keyword. This works well in cases where a subclass may want to override methods from its base classes in order to provide custom implementations. C# also has a concept of using virtual keyword in base class to indicate that a method in the base class can be overridden by the sub class.
Below is the implementation of function overriding in C#:
C#
using System;
class Animal {
public virtual void MakeSound() {
Console.WriteLine("Animal makes a sound");
}
}
class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("Dog barks");
}
}
class Program {
static void Main(string[] args) {
Animal animal = new Dog(); // Upcasting
animal.MakeSound(); // Output: Dog barks
}
}
Explanation: Similar to C++, C# uses the virtual keyword for function overriding. The Dog class overrides the MakeSound() method of the Animal class. When MakeSound() is called on a Dog object, it prints "Dog barks".
Function overriding in Javascript:
Even though JavaScript is not a classical language that supports classical inheritance and function overriding others do JavaScript does support prototype-based inheritance. Function overriding can be implemented in various ways such as changing the prototypes of objects or by using ES6 classes and the keyword extends.
Below is the implementation of function overriding in Javascript:
JavaScript
class Animal {
makeSound() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
makeSound() {
console.log("Dog barks");
}
}
const animal = new Dog();
animal.makeSound(); // Output: Dog barks
Explanation: In JavaScript, you can achieve function overriding using class inheritance. The Dog class extends Animal and provides its own implementation of the makeSound() method. When makeSound() is called on a Dog object, it prints "Dog barks".
Advantages of Function Overriding:
- Code Reusability: Method overriding enables subordinates to extend methods developed in superordinates. This helps in preventing the same piece of code from being written in different classes which deal with similar functionalities.
- Polymorphism: Overriding helps in achieving polymorphism as it allows different methods of the parent class to be invoked depending on the instance of the object that triggered the method.
- Modularity: Function overriding also encourages the concept of modularity in code design because it allows subclasses to override specific methods.
- Specialization: Method overriding can be defined as a process that allows the subclasses in object oriented programming to alter the behavior of the methods inherited from the super classes.
Disadvantages of Function Overriding:
- Complexity: Using deep hierarchy inheritance in combination with function overriding of multiple levels may result in complexity of the source code.
- Maintenance Challenges: Function overriding will make code maintenance more complicated and a change to super class will affect all subclasses that override some methods in super class.
- Lack of Clarity: There are instances where overriding functions may hide the method and what they do, particularly if the methods implemented in the derived classes are entirely unique.
Conclusion
As such, function overriding is a very important aspect in the area of object-oriented programming because it provides a mechanism through which functionality could be provided by the subclasses of an object. This means the creation of code that can be reused, modularized, and demonstrated polymorphic behavior which helps in making the software extensible.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read