The main advantage of rewriting is that it can define the unique features of a subclass:
For example:
Public class father
{
Public void speak ()
{
System. Out. println ("father ");
}
}
Public class son extends father
{
Public void speak ()
{
System. Out. println ("son ");
}
}
This is also called polymorphism. The rewriting method can only exist in an inheritance relationship. The rewriting method can only override non-private methods of the parent class,
In this example, when the father class speak () method is private, the son class cannot override the father class speak () method. In this case, the son class speak () the method is equivalent to a speak () method defined in the son class.
When father class speak () method 1 is final, no matter whether the method is public, protected, or modified by default, the son class cannot overwrite the father class speak () method and try to compileCode The compiler reports an error. For example:
Public class father
{
Fianl public void speak ()
{
System. Out. println ("father ");
}
}
Public class son extends father
{
Public void speak ()
{
System. Out. println ("son ");
}
} // The Compiler reports an error.
When the father class speak () method is modified by default, it can only be in the same package and its subclass is duplicated. If it is not in the same package, it cannot be rewritten.
When the father class speak () method is protoeted, not only is it in the same package, but its subclass is duplicated. It can also be rewritten by the subclass of different packages.
Rewrite method rules:
1. The parameter list must be exactly the same as that of the method to be overwritten. Otherwise, it cannot be called a rewrite but an overload.
2. The return type must always be the same as the return type of the method to be overwritten. Otherwise, it cannot be called an overwrite but an overload.
3. The access modifier must be greater than the access modifier of the method to be overwritten (Public> protected> default> private)
4. The rewrite method cannot throw a new check exception or a broader check exception than the declared method.For example,
A Method of the parent class declares an ioexception check. If you override this method, you cannot throw an exception. You can only throw a subclass exception of ioexception. You can throw a non-checked exception.
The reload rules:
1. Different parameter lists are required;
2. There can be different return types, as long as the parameter list is different;
3. Different access modifiers are available;
4. Different exceptions can be thrown;
The difference between rewriting and overloading is:
Rewriting polymorphism works. Calling methods that have been overloaded can greatly reduce the input of code. Passing different parameters to the same method name can have different functions or return values.
A clear and concise class can be designed with good rewriting and overloading. It can be said that rewriting and overloading play an extraordinary role in coding.