Home > Java > javaTutorial > The difference between rewriting and overloading methods in java

The difference between rewriting and overloading methods in java

伊谢尔伦
Release: 2016-11-21 15:02:50
Original
1485 people have browsed it

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();
         }
}
Copy after login

An error is reported when compiling, as shown in the picture:

The difference between rewriting and overloading methods in java

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();
         }
}
Copy after login

Run successfully

The difference between rewriting and overloading methods in java

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template