java - protected members accessed in derived class using base class instance
You're right that you can't do this. The reason why you can't access the field, is that you're not in the same package as the class, nor are you accessing an inherited member of the same class.
The last point is the critical one - if you'd written
MyCollection2 mc = new MyCollection2();
mc.intg = 1;
then this would work, as you're changing a protected member of your own class (which is present in that class through inheritance). However, in your case you're trying to change a protected member of a different class in a different package. Thus it should come as no surprise that you're denied access.
The Java tutorial says:
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
And in your case, you are accessing the variable in another object. By coincidence it has a class that's the same as the current one, but the visibility checks wouldn't check that.
So, the second time you are denied access, because you are in a different package, and the first time you are given access because you are in the same package (and not because it's a subclass)
If a class member is protected
then there are 2 cases:
- If subclass is in same package
- If subclass is in different package
I. Same package :
- Can access through inheritance
- Can access by creating an instance of parent class
II. Different package :
- Can only access through inheritance
See the table below for all use cases:
Source: SCJP book.