What Is Method Overriding?

In Java and some other advanced object-oriented programming languages, subclasses can inherit methods from the parent class without the need to rewrite the same methods. But sometimes the subclass does not want to inherit the methods of the parent class intact, but wants to make certain modifications, which requires the method to be rewritten. Method rewriting is also called method coverage.

Method rewrite

If a method in the subclass has the same method name, return type, and parameter table as a method in the parent class, the new method will overwrite the original method. If you need the original method in the parent class, you can use the super keyword, which refers to the parent class of the current class.
Some characteristics about method rewriting:
1. The method return value, method name, and parameter list of the two method overrides must be exactly the same (subclass overrides parent method)
2. The exception thrown by the child class cannot exceed the exception thrown by the corresponding method of the parent class (the child class exception cannot be greater than the parent class exception)
3. The access level of a subclass method cannot be lower than the access level of the corresponding method of the parent class (the access level of a subclass cannot be lower than the access level of the parent class)
According to 2, 3, you can determine the first one. The type of the return value of the subclass overriding the method of the parent class cannot be greater than the type of the return value of the method of the parent class, which means that the return value of the method of the child class must be the same as the value of the method of the parent class. Or its subclasses.
Method rewriting is different from method overloading. Method overloading is that the number or type of method parameters is different, and the method name is the same.
Method rewriting is to pay attention to the issue of permissions. The permissions in the subclass cannot be less than the permissions of the parent class. When the permissions of the parent class are private, the child class cannot inherit. It is not possible to produce so-called rewrites. (High and low modifiers: private <default modifier <public)

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?