Explain Method overriding with example?
Question
Explain Method overriding with example?
Solution
Method overriding is a feature in object-oriented programming that allows a subclass to provide a different implementation for a method that is already defined in its superclass. This is done to change the behavior of the method in the subclass.
Here's a simple example in Java:
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
// This method overrides the method in the parent class
@Override
void sound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
myDog.sound(); // Calls the sound() method in Dog class
}
}
In this example, the sound() method in the Dog class overrides the sound() method in the Animal class. When sound() is called on an object of type Dog, the overriding method in the Dog class is executed, and "The dog barks" is printed to the console.
Similar Questions
Method Overriding in Java
Explain method Overloading
What is method overriding?ADeleting a method from a superclass.BChanging the way a method works in a subclass.CRenaming a method in a subclass.DIncreasing the speed of a method.ECalling a method from another method.
What is method overriding in the context of inheritance?a.Calling a superclass method in the subclassb.Changing the method implementation in the subclassc.Removing a method in the subclassd.Changing the method parameters in the subclass
What is Overriding? Hints: Concept, Use Case Syntax and example
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.