Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Protected Inheritance question  RSS feed

 
Dikshant Janaawa
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Can anyone explain why Lynx c cannot access x in LynxKid class?
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See section 6.6.2 of the Java Language Specification...

https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.2

Basically, if class code wants to access a protected member that is in a different package, it must be "responsible for the implementation" ... or it must use a reference type, that IS-A the type where the implementation is located.

In this case, since the code is part of the LynxKid class, and the protected member is in a different package, it needs the reference to be IS-A LynxKid type.

Henry
 
Herland Cid
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

When we talk about protected members of a class, we talk about a package level restriction (if they are in different packages).

The only way this restriction is removed is when we extend the class containing the protected member, that's why Lynx class can have access to the protected member in class Big.

In the other hand, LinxKid attempts to access a protected member it does not directly inherit from.

In resume, this could be solved only in two ways:
1. LinxKid must extend Big
2. LinxKid and Big class must belong to the same package.

Regards
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Herland Cid wrote:
The only way this restriction is removed is when we extend the class containing the protected member, that's why Lynx class can have access to the protected member in class Big.

In the other hand, LinxKid attempts to access a protected member it does not directly inherit from.

In resume, this could be solved only in two ways:
1. LinxKid must extend Big
2. LinxKid and Big class must belong to the same package.


This is *not* true. Protected members can be accessed by all subclasses, even subclasses that don't directly extend from the superclass with the protected field. Take a look at the OP's example again. You will notice that line 6 and 7 compiles. The LinxKid class can access the protected field.

It is only two lines later, when the LinxKid class tries to access the protected field, using a Lynx reference (and hence, violated the rule mentioned), that it fails to compile.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!