Reimplementing the inherited method from the parent class in the child class is called Overriding in Java.
There are certain rules for overriding, the below code points out all of the rules:
Some more rules which may be obvious:
- You cannot override a method marked
final
. - You cannot override a method marked
static
. - If a method can’t be inherited, you cannot override it. As said earlier, overriding implies that you’re reimplementing a method you inherited.
Dynamic Method Invocation: Overridden instance methods are dynamically invoked based on the real object’s type
rather than the reference type. For example, b.eat()
will actually run the Horse version of eat()
.
Q&A
Q1. Will the below code compile?