Java Method Overriding

In this Java article we want to learn about Java Method Overriding, Java Method Overriding is a concept in object oriented programming where subclass provides a specific implementation of a method that is already defined in its superclass. 

 

 

So now let’s create an example on method overriding, in this example we have an Animal class and we have defined a method called makeSound(). Dog class extends the Animal class and overrides makeSound() method with its own implementation.

 

 

Now let’s say we creates an instance of the Dog class and call makeSound() method on it.

 

 

 

This is the complete code for this article, in this example we have an Animal class that defines a method called makeSound(). Dog and Cat classes extends Animal class and override makeSound() method with their own implementations. in the Main class we have created objects of each class and call their makeSound() methods.

 

 

 

This will be the result

Java Method Overriding
Java Method Overriding

 

 

We have saw the example now let’s talk that how does Java determine which implementation of the method to use ? Java uses concept of dynamic method dispatch to determine appropriate method to call at runtime. when a method is called on an object, Java checks the type of the object at runtime and then determines which implementation of the method to use. Method overriding is useful when you want to provide more specific implementation of a method in subclass. for example.

 

 

Learn More

Leave a Comment