Overloading: The method names are the same, but the parameters must be different (different parameters can result in different types, different orders, and different numbers). Overriding (also called overwriting): The subclass inherits the method of the parent class and reimplements the method.
Precautions for using method rewriting:
1. When rewriting a method, there must be an inheritance relationship
2. When rewriting a method, the method name and formal parameters must be consistent.
3. When rewriting a method, the permission modifier of the subclass needs to be greater than or equal to the permission modifier of the parent class.
4. When rewriting a method, the return value type of the subclass must be less than or equal to the return value type of the parent class
5. When rewriting a method, the exception type of the subclass must be less than or equal to the exception type of the parent class.
Here we mainly use the third point to test:
public class a{ public static class People { public void fun(){}; } static class Student extends People { protected void fun(){ System.out.println("dfdfd"); } } public static void main(String[] args){ Student p = new Student(); p.fun(); } }
An error is reported when compiling, as shown in the picture:
The reason is that the permissions of the methods of the parent class are public, and the subclasses are changed to protected, which reduces permission, so it can only be greater than or equal to:
public class a{ public static class People { protected void fun(){}; } static class Student extends People { public void fun(){ System.out.println("dfdfd"); } } public static void main(String[] args){ Student p = new Student(); p.fun(); } }
Run successfully