This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Does not Line 1 show some compilation error, as the instance variable of class A is protected so far as inheritance it will only available in its immediate subclass as its private data.
So, it should not be possible to modify the value of variable a using a reference of class B as that is actually private there.
If I am wrong please correct me with more details if you can.
If you remove the protected modifier from a in your example (so you'll end up with a data member with default access modifier), what will happen with line 1? Compiler error? Compiles just fine? Runtime exception? ...
As it is in same package scope,
the default modifier will be available everywhere in that package.
So, its works fine.
There is nothing like protected member when it is inherited will be private. This part confused me, is that will same when its happened in same package?
The difference between default and protected access modifier is one of the hardest things to master. I even see experienced developers struggle with the distinction.
Default and protected access modifiers are almost identical. A default member may be accessed only if the class accessing the member belongs to the same package (using inheritance and/or reference). So if A and B are in the same package this code will compile and run:
A protected member can be accessed as a default member + can be accessed (but only through inheritance) by a subclass even if the subclass is in a different package. So as an easy reminder: default = package-private and protected = package-private + kids. So the above code will still compile when member a is marked protected.
Because in your example all classes are in the same package the package-private rule applies. The kids-rule is an addition to the package-private one, it's not a replacement. So protected is exactly the same as default, but there is a little bonus. With default access all classes and sub classes can access the member if they are in the same package. A protected member can also be accessed by all classes and sub classes in the same package, but the member can also be accessed by a subclass in another package (but only through inheritance). This example demonstrates this behavior: