在 java 中 return 类型的两种覆盖方法是否可以不同?
Can two overriding methods vary in return type in java?
class ab {
int add(int a, int b) {
return a + b;
}
}
class bc extends ab {
String add(int a, int b) {
return a + " " + b;
}
}
如果我使用的是 JRE 5,此代码是否 运行? JRE7 和 JRE8 中发生了什么?
您只能改变 return 类型,如果它们是相关的(或 协变 使用严格术语)。从广义上讲,这意味着一个是另一个 reference-castable:即一个是另一个的 child class。
所以在你的情况下不是,因为 String
与 int
无关:int
是原始类型。
如果您在子 class 中使用不同的 'return' 类型重新定义一个方法,那么除非 return 类型相似(在您的例如,一个是字符串,另一个是 int - 完全不同的数据类型,因此它不会被覆盖)。
示例:
超级class:
public class mysuper
{
byte newfun(int a)
{
return 11;
}
}
子class:
public class mysub
{
int newfun(int b)
{ // this is over-riding,the body of the function is different and the return type is different but similar
return 12;
}
}
掩盖:
1.In重写,函数return类型完全相同或类似,只是body可能不同。
class ab {
int add(int a, int b) {
return a + b;
}
}
class bc extends ab {
String add(int a, int b) {
return a + " " + b;
}
}
如果我使用的是 JRE 5,此代码是否 运行? JRE7 和 JRE8 中发生了什么?
您只能改变 return 类型,如果它们是相关的(或 协变 使用严格术语)。从广义上讲,这意味着一个是另一个 reference-castable:即一个是另一个的 child class。
所以在你的情况下不是,因为 String
与 int
无关:int
是原始类型。
如果您在子 class 中使用不同的 'return' 类型重新定义一个方法,那么除非 return 类型相似(在您的例如,一个是字符串,另一个是 int - 完全不同的数据类型,因此它不会被覆盖)。
示例: 超级class:
public class mysuper
{
byte newfun(int a)
{
return 11;
}
}
子class:
public class mysub
{
int newfun(int b)
{ // this is over-riding,the body of the function is different and the return type is different but similar
return 12;
}
}
掩盖:
1.In重写,函数return类型完全相同或类似,只是body可能不同。