• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Inheritence question

 
Ranch Hand
Posts: 271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From JQPlus mock test:
Consider following two classes:
What will be the output of compiling and running class B ?

The correct answer is that it won't compile.The explanation says that

Although, class B extends class A and 'i' is a protected member of A, B still cannot access i, (now this is imp) THROUGH A's reference because B is not involved in the implementation of A.
Had the process() method been defined as process(B b); b.i would have been accessible as B is involved in the implementation of B.


How can this be when a protected field is accessible from a subclass?I don't really understand the given explanation.
jeff mutonho
Edited by Corey McGlone: Added CODE Tags
[ May 01, 2004: Message edited by: Corey McGlone ]
 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are trying to access A-type object that is outside of the B class.
The way inheritance works is that a subclass can extend functionality of the superclass, not have unlimited access to protected memebers of any object of the superclass.
Instead of
a.i = a.i*2;
it should be:
super.i = super.i*2;
or simply:
i = i*2;
Andris
[ May 01, 2004: Message edited by: Andris Jekabsons ]
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm surprised that the similar code but without packages has been compiled.

There's a little clue in JLS pointed that protected affects only access outside the package. Correct me please, if I'm wrong.

6.6.2 Details on protected Access
A protected member or constructor 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.

 
If you settle for what they are giving you, you deserve what you get. Fight for this tiny ad!
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic