• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic