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
Functions in Programming
Functions in programming are modular units of code designed to perform specific tasks. They encapsulate a set of instructions, allowing for code reuse and organization. In this article, we will discuss about basics of function, its importance different types of functions, etc.Functions in Programmin
14 min read
Functions in R Programming
A function accepts input arguments and produces the output by executing valid R commands that are inside the function. Functions are useful when you want to perform a certain task multiple times. In R Programming Language when you are creating a function the function name and the file in which you a
8 min read
Function Parameters in Programming
Function Parameters are used to declare the input values that a function expects. The parameters of a function play a significant role while defining the function so that whenever we call the function, we ensure that necessary arguments are passed to the function. In this article, we will dive deep
3 min read
Function Overloading vs Function Overriding in Programming
Function Overloading allows multiple functions with the same name but different parameters, enabling the same function name to perform different tasks based on input parameters. On the other hand, Function Overriding is a feature that allows a subclass to provide a specific implementation of a metho
3 min read
Types of Functions in R Programming
A function is a set of statements orchestrated together to perform a specific operation. A function is an object so the interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions. The function in turn performs the task a
6 min read
Function Calling in Programming
Function Calling in programming refers to the process of invoking or executing a function within a program. Functions are blocks of code that perform a specific task, and they allow programmers to organize their code into reusable units, making it easier to manage and maintain. Table of Content What
4 min read
Operator Overloading in Programming
Operator Overloading is a feature in some programming languages used to redefine or "overload" the standard behavior of operators (such as +, -, *, etc.) to work with user-defined data types. This is useful when working with objects of custom classes. In this article, we will learn about the basics
4 min read
Function Arguments in Programming
Function Arguments are values or variables passed into a function when it is called. The arguments to a function play a significant role as they provide the necessary input for the function to perform its intended task. In this article, we will discuss what are Function Arguments in Programming acro
3 min read
Function Arguments in R Programming
Arguments are the parameters provided to a function to perform operations in a programming language. In R programming, we can use as many arguments as we want and are separated by a comma. There is no limit on the number of arguments in a function in R. In this article, we'll discuss different ways
4 min read
Solidity Function Overloading
Function overloading in Solidity lets you specify numerous functions with the same name but varying argument types and numbers.Solidity searches for a function with the same name and parameter types when you call a function with certain parameters. Calls the matching function. Compilation errors occ
1 min read