Home >>Java Tutorial >Method Overriding in Java
Method Overriding is a condition in the Java language in which a subclass that is also known as the (child class) has the same method that has been declared in the parent class. In simple words, it can be understood as a case where a subclass provides the specific implementation of the method that has already been declared by one of its parent class. Please note that overriding generally means to override the functionality of an existing method in the terms of object-oriented.
The main advantage or we can say the benefit of method overriding is its ability to define a behavior that's specific to the subclass type that simply means that a subclass can implement a parent class method that will be based on its requirement. Overriding generally means to override the functionality of an existing method in Java in terms of object-oriented.
Here is an example of the method overriding in the Java language that will help you to understand the application aspect of it:
class Animal { public void move () { System.out.println ("Animals can move"); } } class Cat extends Animal { public void move () { System.out.println ("Cats can walk and run"); } } public class TestCat { public static void main (String args[]) { Animal a = new Animal (); // Animal reference and object Animal b = new Cat (); // Animal reference but Cat object a.move (); // runs the method in Animal class b.move (); // runs the method in Cat class } }
Here is the explanation of the above example; even though b is a type of Animal and it runs the move method in the Cat class. The main reason behind it is that in the compile time, the reference type is generally the one on which the check is performed. However, JVM generally figures out the object type and it would run the method that generally belongs to that particular object at the runtime. Hence, the program will basically compile in order as the Animal class has the method named move. Therefore, at the runtime, this will run the method that is specific for that object only.
There are certain rules that are generally implemented when the method overriding is used in the Java languages that are depicted below: