2016-03-01 83 views
4

我是一名Java初学者,在学习过程中遇到此程序。无法在子类中创建返回类型对象的方法

一级是超级班。第二类延伸一,三延伸二。

class One { 
public One foo() { 
return this; 
} 
} 
class Two extends One { 
    public One foo() { 
    return this; 
    } 
} 
class Three extends Two { 
    public Two foo() { 
    return this; 
    } 
} 

在这里,在第三类,当我创建返回类型二的方法foo没有编译错误但是当我做如下图所示的返回类型“对象”,有一个编译错误。

class Three extends Two { 
    public Object foo() { 
    return this; 
    } 
} 

从我到目前为止了解到的情况来看,Object是所有类的超类。为什么我不能在子类中创建返回类型为“Object”的方法?

回答

4

它失败了,因为返回的类应该是One或其子类(例如Two),它也保证也是One;不是它的超类(例如Object),就编译器而言,它可以是除One之外的其他任何东西。

class Three extends Two { 
    public Two foo() { // works because Two is a subclass of One 
    return this; 
    } 
} 

class Three extends Two { 
    public Object foo() { // fails because Object is not a subclass of One 
    return this; 
    } 
} 
0

如果你有一个想法有关共同的变体光盘return typeOverriding念来过,那么你必须知道,在孩子class压倒一切的方法必须return这样一种类型,或者是为同super类方法包含或任何child Class(协变类类型)。 Co-Variant Return Type Example

class Three extends Two { 
    public Object foo() { 
    return this; 
    } 
} 

注: - 在此代码你返回object类。这是一个super所有类不是儿童所以它的一种非法编译代码。

你可以试试这个...

class Three extends Two { 
    public Two foo() { // works because Two is a subclass of One 
    return this; 
    } 
} 

OR

class Three extends Two { 
     public Three foo() { // works because Three is a subclass of Two & One 
     return this; 
     } 
    } 

两者都可以胜任。根据您的需要使用。谢谢

+0

为什么你回滚我所做的编辑?重新引入拼写错误,格式不正确,噪音等?你知道Stack Overflow是如何工作的,对吗?鼓励每个人都改进帖子? –