这可能只是语义,可能是一个愚蠢的问题,但我很好奇以下内容是否会被视为重载:
public String name = "name";
public void printName() {
System.out.println(name);
}
protected String printName(String extra) {
System.out.println(name + extra);
return name + extra;
}
我读到的所有内容都说必须更改参数才能发生重载,并且只要参数不同,更改访问修饰符和返回类型就不会导致编译错误,但我无法弄清楚后者是否仍被视为重载。
最佳答案
如有疑问,JLS will help :
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.
所以这不是“更改参数”,而是不等效。要了解那是什么,请访问 to another chapter ,这表示:
Two method signatures m1 and m2 are override-equivalent iff either m1 is a subsignature of m2 or m2 is a subsignature of m1.
同一章解释了子签名是什么:
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 与 m1 具有相同的签名,或者
m1 的签名与 m2 签名的删除(第 4.6 节)相同。
如何解释上述方法是留给您的练习。
关于java - 重载具有不同访问修饰符、返回类型和参数的方法是否仍然被视为重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67991354/