I've a class defined this way:
package prueba;
public class OtraClase {
[...]
protected int num3;
[...]
And another class defined this way:
package otro;
import prueba.*;
public class OtraClaseMas extends OtraClase{
But if in that last class I create an OtraClase object I cannot do something like this:
createdObjectOfOtraClase.num3=1;
And I think that according to the documentation I should be able to, here. It says that the protected modifier allows for access by a subclass of its class in another package. And as much as I look at it I don't see it being another thing than exactly a subclass of its class in another package.
Am I misunderstanding something?
Edit: I'm either using the constructor of the class and in another different function and it doesn't work in neither place.
Code for the constructor:
public OtraClaseMas(int num, int num2,int num3)
{
super(num, num2,num3);
OtraClase oc=new OtraClase(1,1,1);
//oc.num3=1; This doesn't work
}
Code for the method:
public void foo()
{
OtraClase oc=new OtraClase(1,1,1);
//oc.num3=1; This doesn't work
}
Are you sure you are initializing the object correctly , because the following works perfectly fine
A
protected
variable can be accessed from the same package or by the derived classes the same way they access their own members, but if you create an instance of the super class outside of the package of the superclass, you wont be able to access it even if you are extending this same superclassSo the thing is, if you want to access a parent's
protected
variable, you can't use reference (as you're trying to infoo()
andOtraClaseMas()
). What documentation is trying to tell is that if you want, you can directly use the variables as class variables as shown below-However, if the reference was created in the same package as parent class (
prueba
in your case), then theprotected
variable will be accessible.