• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance for protected member  RSS feed

 
Arend van der Kolk
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I still do not understand why "Acc obj = new Test()" will not give access to the protected integer in the superclass but "Test obj = new Test()" will give access.

Acc obj = new Test(); <- NO acces to protected integer
Test obj = new Test(); <- YES acces to protected integer



 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are running into a somewhat obscure rule ...

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

Java only allows the subclass to access protected members, that are in a different package, if it is "responsible for the implementation".... ie. if it can determine the type IS-A the subclass. If you want to access the protected member, while using a superclass reference, you will need to cast it first.

Henry
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's simply a rule of the language. Protected members may only be accessed when the type of the expression on which you perform the access is strictly a subclass of the class that declares the protected member.

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

[edit]

Beaten to the punch.
 
Liutauras Vilda
Sheriff
Posts: 4928
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is because:
protected variables can be accessed either in the same package or via extended class in any package

Now, when you do Acc a = new Test(); a reference variable is of type Acc, not of type Test. And since Acc class is declared in package p1 and you instantiated object in package p2, you can't access it unless you'd cast it to Test type in which way you'd be accessing it via extended class. i.e.
 
Arend van der Kolk
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for explaining, it is more clear to me now that accessing via extended has to go via the type of the Object on which you perform the access
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!