Method overriding means method same name with same signature(argument) but in different inherited class.
Method overriding is a concept in Java where a subclass provides its own version of a method that is already defined in its superclass.
When a subclass overrides a method, it provides a new implementation for that method while keeping the same name, return type, and parameter list.
This allows you to customize the behavior of methods in your subclass while maintaining a common method name and signature.
Why is Method Overriding Useful?
Method overriding is useful because it allows you to create specialized behavior for a method in a subclass, making your code more flexible and extensible.
It's a way of implementing polymorphism in Java, where different objects can behave differently based on their specific types.
Example of Method Overriding:
Let's consider an example with a simple class hierarchy to understand method overriding better:
In this example:
We have an Animal class with a method makeSound that prints a generic message.
We create a subclass Dog that extends Animal.
In the Dog class, we use the @Override annotation to indicate that we are overriding the makeSound method.
We provide a specific implementation for a dog's sound, which is barking.
In main class what is happening.
We create an instance of Animal called myAnimal and call its makeSound method, which prints the generic animal sound.
Then, we create an instance of Dog called myDog and call its makeSound method. This time, the output is "Dog barks!" because the Dog class has overridden the makeSound method.
0 Comments
If you have any doubts, Please let me know