使用不同的访问修饰符、return 类型和参数重载方法是否仍被视为重载?
Is overloading a method with different access modifier, return type, and parameters still considered overloading?
这可能只是语义问题,可能是个愚蠢的问题,但我很好奇以下内容是否会被视为重载:
public String name = "name";
public void printName() {
System.out.println(name);
}
protected String printName(String extra) {
System.out.println(name + extra);
return name + extra;
}
我读过的所有内容都说必须更改参数才能发生重载,并且只要参数不同,更改访问修饰符和 return 类型就不会导致编译错误,但是我不知道后者是否仍会被视为超载。
如有疑问,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.
同一章解释了 subsignature 是什么:
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 与 m1 具有相同的签名,或者
m1的签名与m2签名的擦除(§4.6)相同
您如何解释上述方法是留给您的练习。
这可能只是语义问题,可能是个愚蠢的问题,但我很好奇以下内容是否会被视为重载:
public String name = "name";
public void printName() {
System.out.println(name);
}
protected String printName(String extra) {
System.out.println(name + extra);
return name + extra;
}
我读过的所有内容都说必须更改参数才能发生重载,并且只要参数不同,更改访问修饰符和 return 类型就不会导致编译错误,但是我不知道后者是否仍会被视为超载。
如有疑问,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.
同一章解释了 subsignature 是什么:
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 与 m1 具有相同的签名,或者
m1的签名与m2签名的擦除(§4.6)相同
您如何解释上述方法是留给您的练习。