2013-05-25 35 views
2

例如,我有类人,我想覆盖克隆()函数。clone()的返回类型应该是什么?

clone(),Object或Human的返回类型应该是什么?我知道返回类型在重写过程中没有任何作用,因为它不在函数的签名中。

例如,在类人应该我有

public Object clone() throws CloneNotSupportedException { 

    Human h = (Human)super.clone(); 

    h.age = age; 
    h.name = name; 


    return h; 
} 

,然后在主

public static void main() throws CloneNotSupportedException { 



    Human h = new Human("Slavco", 49); 

    Human z = (Human)h.clone(); 
} 

OR

public Human clone() throws CloneNotSupportedException { 

    Human h = (Human)super.clone(); 

    h.age = age; 
    h.name = name; 


    return h; 
} 

,并在主

public static void main() throws CloneNotSupportedException { 



    Human h = new Human("Slavco", 49); 

    Human z = h.clone(); 
} 
+0

是什么原因*不*返回'Human'?是的,返回类型*确实有重写规则:它应该是原始返回类型的子类型。 – Elazar

+0

使用第二种方法。 –

+0

它们都重写默认的Object构造函数,但在方法定义中返回Human更清晰,它还允许您在人类对象上调用clone并且不必投射。 – greedybuddha

回答

2

返回Human会让你的生活更轻松(可能为你节省很多铸件),并且没有任何缺点。
我肯定会推荐这种方法。

+0

它也可以捕捉到愚蠢的错误。 – Elazar

+0

您是否试图以这种方式实际实现clone()? –

+1

@DonRoby编译自'Human'是'Object'的子类。返回类型不一定是相同的。 –

相关问题