Method overriding in Java is a feature that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. When a subclass defines a method with the same name, return type, and parameters as a method in its superclass, it overrides t
Tweet
Method overriding is useful in situations where a subclass needs to modify the behavior of a method that is already defined in its superclass. By providing its implementation of the method, the subclass can customize the behavior of the method to suit its needs.
Here’s an example of method overriding in Java:
csharp code
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
In this example, we have a superclass called Animal
and a subclass called Dog
. The Animal
class has a method called makeSound()
that prints a message to the console. The Dog
class overrides this method by providing its implementation of the method that prints a different message to the console.
When we create an instance of the Dog
class and call the makeSound()
method on it, Java will call the implementation of the method in the Dog
class, rather than the implementation in the Animal
class. This is because the Dog
class overrides the makeSound()
method in the Animal
class.
Method overriding is an important concept in object-oriented programming and allows developers to create subclasses that customize the behavior of methods in their superclass. By overriding methods, developers can create more flexible and adaptable code that can be customized to
Tweet