访问其他包中的受保护方法?
如果我说
class A{
}
那么它隐式继承了 Object 类。所以我的类如下:
class A{
protected Object clone(){
} /// Here i am not overridning
//All the other methods (toString/wait/notify/notifyAll/getClass)
}
现在为什么我不能访问类 B 中的 clone() 方法,该方法位于类 A 的同一包中。
Class B{
A a = new A();
a.clone();
**
}
//** 说克隆受到保护在对象类中。但我没有访问对象的克隆方法。无论如何,我在这里调用 A 类的克隆方法,但我还没有重载。
If I say
class A{
}
then it implicitly inherits Object class.So I am having the class as below:
class A{
protected Object clone(){
} /// Here i am not overridning
//All the other methods (toString/wait/notify/notifyAll/getClass)
}
Now Why cant I access the clone() method in Class B which is in the same package of class A.
Class B{
A a = new A();
a.clone();
**
}
//** Says clone is protected in Object class . But I am not accessing Object's clone method .Here I am invoking class A's clone method anyway which I havn't overloaded yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
protected
方法是在java.lang.Object
中定义的,因此您无法从另一个包中调用它 - 只能从子类中调用。您在对
A
的引用上调用它,但它是java.lang.Object
的方法,直到您覆盖它。当重写
clone()
时,您应该将修饰符更改为public
并实现Cloneable
。然而,使用clone()
方法并不是一个好主意,因为它很难正确实现。使用 commons-beanutils 进行浅克隆。确保区分“覆盖”和“重载”。
The
protected
method is defined in thejava.lang.Object
, so you can't invoke it from another package - only from subclasses.You are calling it on a a reference to
A
but it is a method ofjava.lang.Object
, until you override it.When overriding
clone()
, you should change the modifier topublic
and implementCloneable
. However using theclone()
method is not a good idea, because it's very hard to implement it correctly. Use commons-beanutils to make shallow clones.Make sure you make distinction between "overriding" and "overloading".
这完美的工作
this perfectly work