Why can we access the clone()
method using super.
notation but cant access it by creating new object of type Object. For example if I do something like
Object obj = new Object();
then (using Eclipse) I cannot view the clone()
method using the dot operator, which shows that obj is not able to view protected members of Object
class (only public methods are visible).
Now if I were to use the super
keyword i.e use super.
I am able to view protected methods as well.
So my question is that in a class which does not explicitly inherit (extend) other class -- i know that it gives an implicit call to the Object class constructor, i.e. the Object class is its superclass-- why can super keyword access the protected members of Object class, but same is not achieved by creating instance of Object class (only the public members are visible to the instance of Object class)?
Here is clearer code (although it makes no sense but the first part complies and other doesn't):
public class temp {
public temp() {
// TODO Auto-generated constructor stub
TestBikes t1 = new TestBikes();
Object ob1 = new Object();
try {
t1 = (TestBikes)super.clone(); //SUPER KEYWORD IS ABLE TO ACCESS
//PROTECTED MEMBERS OF Object
//CLASS
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
t1 = (TestBikes)ob1.clone(); // HERE IS THE ERROR SAYING clone()
// FROM Object CLASS IS NOT VISIBLE
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected
means only accessible by a sub-class (or a class in the same package) So you can access it in a sub-class using this
or super
or nothing, but not another instance.
Your example compiles but it won't run.
try {
t1 = (TestBikes)super.clone(); // creates a clone of temp, not a TestBikes
t1 = (TestBikes)this.clone(); // does the same thing
t1 = (TestBikes)clone(); // does the same thing
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BTW: I know this is just an example but cloning an object in it's constructor is a bad idea.
It has to be protected so you can access it in subclasses which implement Cloneable
. However, not all objects are cloneable so it is not generally accessible.
Using super
can access protected methods. Using a reference to make a method requires the method be accessible e.g. public or package local and in the same package.
AFAIK, It is generally accepted that the clone()/Cloneable API is broken and should be avoided (except for primitive arrays) e.g. The Cloneable interface doesn't have a Object clone();
method to make it public and it returns Object
which have to cast.