Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

The Protected method access

 
Greenhorn
Posts: 22
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
  In the Jeanne Boyarsky & Scott Selikoff's book OCA Study guide for Java SE 8 in Chapter 4 is the following code -



This code doesn't compile because we are not in the Goose class. The floatInWater() method is declared in Bird. GooseWatcher is not in the same package as Bird, nor does it extend Bird. If I put the GooseWatcher class in the same package as Bird the code works but even if I extend GooseWatcher as subclass of Bird (in a different package) the last line doesn't compile! ... Can someone please explain why. Thanks in advance.

Note:- pond.goose.Goose is a subclass of pond.shore.Bird class. While the GooseWatcher class is in pond.duck package.
 
author
Posts: 23878
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Prabir Sarkar wrote:If I put the GooseWatcher class in the same package as Bird the code works



This works because the protected access level is less restrictive than the default access level, which gives access to classes in the same package.

Prabir Sarkar wrote:if I extend GooseWatcher as subclass of Bird (in a different package) the last line doesn't compile! ... Can someone please explain why.



It doesn't compile because you forgot about the "responsible for the implementation rule". See here ... https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.2

If you had used a GooseWatcher instance (and reference to it), then your code is responsible for the implementation, and the access is allowed.

Henry
 
Prabir Sarkar
Greenhorn
Posts: 22
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks for your help Henry.
 
It runs on an internal combustion engine. This ad does not:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic