为了账号安全,请及时绑定邮箱和手机立即绑定

为什么不可以直接通过子类的对象cl.clone()来调用clone()方法呢?why?

为什么不可以直接通过子类的对象cl.clone()来调用clone()方法呢?why?

C
眼眸繁星 2023-04-24 15:11:20
class cloneClass implements Cloneable{int x=0;int y=9;protected void protectedMethod(){System.out.println("calling ProtectedMethod");}Object getObj() throws CloneNotSupportedException{return clone();}}class extendProtectedClass extends cloneClass{}public class Test{public static void main(String [] args){cloneClass cl=new cloneClass();try{cloneClass cl2=(cloneClass)cl.clone();//通过cl.clone()条用Object.clone()方法出错System.out.println(cl2.x);}catch(CloneNotSupportedException ex){ex.printStackTrace();}/*extendProtectedClass ep=new extendProtectedClass();ep.protectedMethod(); //可以通过子类的对象直接调用父类的保护方法protectedMethod()*/}}问题:为什么不可以直接通过子类的对象cl.clone()来调用clone()方法而要通过子类的方法来简介调用我写的Object.clone()是为了说Object类的clone()方法,不是说通过Object类名来调用clone()方法。实际上我是用对象cl.clone()调用
查看完整描述

2 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

protected Object clone() ;
Object类中定义的clone()方法声明为protected,只能被同一包下的类及子类调用,通过cloneClass.clone()调用因为没有可见的clone()方法,会提示no such method.
你要通过(cloneClass)cl.clone()调用的话,在cloneClass内中声明
Object clone() {}重载clone()方法,去掉protected声明

查看完整回答
反对 回复 2023-04-27
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

Object类中没有静态方法clone(),当然不能这样调用。

查看完整回答
反对 回复 2023-04-27
  • 2 回答
  • 0 关注
  • 112 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信