gpt4 book ai didi

java - 这怎么称为重载 - Java

转载 作者:行者123 更新时间:2023-12-02 12:21:04 25 4
gpt4 key购买 nike

我有一个 BindingSample 类,其方法不带参数

public class BindingSample {
public void printMsg(){
System.out.println("Binding Sample no parameter");
}
}
<小时/>

另一个类扩展了 BindingSample 并使用相同的方法签名,但向其中添加了一个参数

public class application extends BindingSample {

public void printMsg(int i){
System.out.println("Changed my value " + i);
}

public static void main(String[] args) {
application app = new application();
app.printMsg(5);
}
}

输出更改了我的值 5

为什么参数不同却能起作用?为什么叫重载呢?我不认为它是重写的,因为要重写方法,方法签名及其参数应该相同。

最佳答案

Why did it work even if the parameters are different?

您的application 类有一个printMsg 方法,该方法采用单个int 参数。因此 app.printMsg(5) 有效。

请注意,进行以下更改将导致您的代码无法通过编译:

BindingSample app = new application();
app.printMsg(5);

现在编译器在 BindingSample 类中找不到采用 int 参数的 printMsg 方法。

And why is it called overloading? I don't think it's overriding because to override a method, the method signature and its parameter should be the same

重写和重载是两个不同的概念。

当多个方法共享相同名称但具有不同数量的参数或不同类型的参数时,就会发生方法重载。

您的 application 类有两个带有不同数量参数的 printMsg 方法(其中一个是从其父类(super class)继承的)。因此这是方法重载。

关于java - 这怎么称为重载 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45780998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com