Method overriding in java
- Declaring a method in sub class which is already present in parent class is known as method overriding.
- Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class.
- In this case the method in parent class is called overridden method and the method in child class is called overriding method.
Purpose of method overriding
- The main purpose of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code.
- This is helpful when a class has several child classes, so if a child class needs to use the parent class method, it can use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the parent class code.
Difference between Redefining and Overriding
- The term “redefinition” isn’t usually used with regards to Java methods and inheritance. There are two terms that are commonly used: “override” and “overload.”
- Redefining and Overriding comes with in the same scenarios. Only difference is that if methods used are Static, its redefining.For Example,
Note: Static methods looks as if they are over-rided but they are actually redefined.
- Redefining is with Static Methods.
- Static methods are associated with Class and not with Object, so we do not override as per instance for run-time.
- In case of static we are just redefining the method.
Re-defining a Inherited Method
- Re-defining involves a inherited method like Replacement and Refinement
- The inherited method of parent class with a behavior(functionality) which is completely different from corresponding parent method and a sign for this process is not calling super.method() in the body of child method.
- The method from parent with a functionality related to parent method functionality, sign of this process is calling generally super.method() in the body of child method.