Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

OCP Java 8 Programmer II Stude Guide - CH1 - Access Modifiers Page 3  RSS feed

 
Balaji Avudaiappan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I cleared OCA and started to prepare for OCP. I am having a hard time understanding the concepts given in Page 3 of OCP Java 8 Programmer II Stude Guide.

We have a class BigCat.



There is another class Lynx in another package which extends BigCat


There is another class CatAdmirer within the same package "cat"



Question 1:
According to the book, this line will not compile as we are accessing it via a variable and so it does not benefit from protected. If I make hasFur variable static in BigCat, I can access the variable.
Why does the code not compile when the variable is non-static and why the code compiles fine when the variable is static?
I am accessing hasFur using a variable in both cases.

Question 2:
Here, I am accessing hasPaws via variable too. If protected variables are not visible when accessed via variable why is package-private variable visible when access via variable?

Please help.
 
Henry Wong
author
Sheriff
Posts: 23260
124
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Balaji Avudaiappan wrote:
Question 1:
According to the book, this line will not compile as we are accessing it via a variable and so it does not benefit from protected. If I make hasFur variable static in BigCat, I can access the variable.
Why does the code not compile when the variable is non-static and why the code compiles fine when the variable is static?
I am accessing hasFur using a variable in both cases.


Java has an somewhat obscure rule requirement for protected variables... https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.2

Specifically, a protected member of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

In this case, "responsible for implementation" means that the code must use a reference that IS-A Lynx. In other words, this should work...

Henry
 
Onion rings are vegetable donuts. Taste this tiny ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!