One thing I have learnt is private
in java doesn't really mean same thing as that in C++. private
in java is class-based, not object-based.
i.e I can access another objects private member directly using "object dot notation" provided that I do so within the class of that object.
However, protected
is not so clear.
We will have to consider two packages here : pack1
and pack2
We declare classes Alpha
and Beta
in pack1
package
and declare AlphaSub
which extends Alpha
from pack1
, and Gamma
which also extends from Alpha
in pack2
package.
!
Here is the class code, I have only included classes relevant to the issue here : Alpha
, AlphaSub
and Gamma
package pack1;
public class Alpha{
private int alphaPrivate;
public int alphaPublic;
protected int alphaProtected;
int alphaPP;
protected int alphaProtected(){
return 1;
}
private int alphaPrivate(){
return 1;
}
}
package pack2;
import pack1.Alpha;
public class AlphaSub extends Alpha{
int alphasubPP;
private int alphasubPrivate;
protected int alphasubProtected;
public int alphasubPublic;
public void meth() throws CloneNotSupportedException{
new AlphaSub().alphaProtected(); //OK
new Gamma().alphaProtected(); /*COMPILE ERROR. */
}
}
So apparently even though both AlphaSub and Gamma inherits alphaProtected()
from Alpha
, one cannot invoke Gamma's inherited alphaProtected()
from AlphaSub ..
If this is the case that protected method of a class can only be called from within that class, wouldn't invocation of clone
[inherited by every class from Object
class] from another class be impossible ??
Someone can please clarify ?