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:
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
}
}
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 programming
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.
Table of Content
- What is Function overriding?
- Function overriding in C++
- Function overriding in Java
- Function overriding in Python
- Function overriding in C#
- Function overriding in Javascript
- Advantages of Function Overriding
- Disadvantages of Function Overriding