Saturday 16 January 2010

Behavior of "inherited protected" variable in Java

Something to remember before going ahead –
There are 2 basic aspects of a variable– inheritance (can be inherited or not; with values – yes/no) and access (can be accessed or not; with values – default/public/private - ignore protected for now)

Consider 2 scenarios:
Scenario 1:

As shown in the above figure –
Result is -
B inherits x, C can access x through object of A and through object of B both.
D inherits x.
E cannot access x at all.

Scenario 2:

As shown in the above figure –
Result is:
B, C inherit x.
Class D cannot access x at all.

Conclusion:
This is about variable x of B.
When protected variable is inherited inside package (Scenario 1), it behaves like default for access and yes for inheritance.
When protected variable is inherited outside package (Scenario 2), it behaves like private for access and yes for inheritance.

Thus, the table is as follows - (click on the table image)

No comments: