Home  >  Article  >  Java  >  06.Java Basics - Overloading & Rewriting

06.Java Basics - Overloading & Rewriting

黄舟
黄舟Original
2017-02-27 10:23:241231browse

Basic concept

Overloading is Overload; rewriting is Override.

The difference is: overloading occurs in the same class; overwriting occurs in the inheritance process.


Overload

Overloading has the following characteristics:

  • It occurs in the same class

  • The function names of the overloaded functions are the same, but the function parameters (number and type) are different.

  • Overloading has nothing to do with the return type

Let’s explore it through an example.

public String print(String word) {    return word;
}// ①函数名称相同,参数个数不同public String print(String word, String title) {    return word + title;
}// ②函数名称相同,参数类型不同public String print(int num) {    return num + "";
}// ③函数名称相同,参数类型、个数不同public String print(int num, int num2) {    return num + num2 + "";
}// ④与返回类型无关public int print() {    return 100;
}

Override

Override has the following characteristics:

  • Method requirements for override to occur The method name, return type, and number/type of parameters must be exactly the same. The

  • method can use the annotation @Override to verify whether it is an override.

  • The access rights of subclass methods are greater than those of the parent class.

  • Subclass methods can only throw smaller exceptions or no exceptions than parent class methods.

  • The overridden method cannot have final, private, static modifiers. Because methods modified with final or private cannot be inherited, and static methods are only related to classes. They are rewritten in form, but in fact the subclass just defines its own static method.

Let’s look at an example of rewriting:

class Parent {
    String word ="Parent";    void print(){
    }
}

class Son extends Parent {
    String word ="Son";    @Override
    void print(){
        System.out.println(word);
    }
}

class Grandson extends Son {
    String word ="Grandson";    @Override
    void print(){
        System.out.println(word+"-"+super.word);
    }
}

The above is the content of 06.Java Basics - Overloading & Rewriting. For more related content, please pay attention to PHP Chinese website (www.php.cn)!


Statement:
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