Suppose the classes below are in different files:

 
package randomPackage;
public class A
{
	float f1;
	protected int i1;
}

// note that class B belongs to the same package as class A
package randomPackage;
public class B
{
	public void someMethod()
	{
		// create an instance of class A
		A anInstance = new A();

		anInstance.f1 = 19;
		anInstance.i1 = 12;
	}
}

public class C extends A
{
	public void someOtherMethod()
	{
		i1 = 89;
	}
}

Is there anything wrong with the code above?

Before we start, we want to point out that both classes A and B belong to the same package called ‘randomPackage’.

Looking at the declaration of ‘f1′ in class A, you’ll notice that it has no access modifier (like public or private). When an access modifier is omitted from a variable, it means that the variable has default, or package, access. When a variable has package access, it means that any other class defined in the same package will have access to that variable by name. And, any class not defined in the same package will not be able to access it by name. Because class B is in the same package as class A, it can access the f1 variable directly by name. So, nothing is wrong with that piece of code.


Now, notice that class B accesses the variable ‘i1′, which is declared in class A. Looking at the declaration of the variable in class A, we notice that it uses the protected access modifier. So, the question is whether or not ‘i1′ is accessible by name in class B? The answer is yes, because in Java any method or instance variable that is declared as protected can be accessed by name in its own class definition, in any class derived from it, and by any class that’s in the same package. And because class B is in the same package as class A, class B can access any variable that’s declared as protected in class A, which in this case is ‘i1′.

Finally, we can see that ‘i1′ is also being accessed in class C, which derives from class A. This is a legitimate access of ‘i1′, since it is declared as protected in class A. And, as the rule above states, any instance variable declared as protected can be accessed in a derived class.

So, we can conclude that there is nothing wrong with the code above.