protected method can only accessed out side the package through inheritance. i.e. by making sub class.
Hope this clear to you.
I'm getting a bit confused by this... I am very well aware of the protected access modifier only allowing access through inheritance, ie: by calling the subclass's own (inherited) method. However...
This is an instance method we are talking about, and the fact is the instance in question is an instance of B, while ofcourse its ref variable is of type A... I'm still getting a bit confused here because if I compare this with a static class method, which cannot be overridden only "redefined", then yes the ref var type is the deciding factor for which static method gets executed...
But here we are talking about an instance method, one which belongs to an object which in fact we can execute the method on... My question becomes, shouldn't the runtime object's access modifier of the method in question be the deciding factor, as opposed to the reference variable type's access modifier, which seems to be the case?
Appearently it's not. Casting the reference variable to a B-type, makes it possible to invoke the method, but the cast appears to be necessary... I just find this a little odd, since once again we are talking about an instance method that has been overridden and I feel like there should be made a runtime check of the access modifier.
Just so there are no confusions, here's the type of code im referring to:
Joined: Apr 25, 2010
A z = new B();
((B)z).m(); // works fine, but not without the cast...
You must make a downcast because during compile time, the compiler look into reference type, so in our case it does not see the m() method as it has protected access, which means it can gain the access through inheritance only, not through make new instance by using new.