File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes K&B Ch10#8 protected access question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "K&B Ch10#8 protected access question" Watch "K&B Ch10#8 protected access question" New topic

K&B Ch10#8 protected access question

Mike Mitchell
Ranch Hand

Joined: May 28, 2008
Posts: 38
Hi guys. Trouble understanding question #8 in Ch10 of the Kathy and Bert SCJP book, included below. I thought the whole idea of protected was to allow access, through inheritance (i.e., a child reference), outside of the package to member attributes and methods. If that's correct, how is that consistent with this example?

After typing this up, I think I see it ... the problem seems to be TestXcom is in a different package. protected means that if a child is in a different package than its parent, the child still has access to protected elements of its parent (though only through a reference of the child type). That privilege doesn't extend to a non-package object who happens to rightly hold a reference to the child.


K&B Ch10#8

Given three files:

Which inserted at will allow all three files to compile? (Choose all that apply.)





E. None of these options will allow the code to compile.

The correct answer is B justified as "The public access modifier is the only one that allows code from outside a package to access methods in a package -- regardless of inheritance."
[ July 20, 2008: Message edited by: Mike Mitchell ]

subhasish nag
Ranch Hand

Joined: Apr 25, 2008
Posts: 101
Hi Mike,
here the conception for Protected access means ,it is only accesible in same package and clild classes in other package. And here you try to access it outside the package and even not from child class.Similarly if you want to access private member outside the class ,even if you have any valid instance of that class you will not be able to access that member.So method pm() is only accesible in packageB and inside child class in packageA
one eg is given below#

class Child{
private int a=5;
protected int AB(){return a;}
public class Test extends Child{
public static void main(String[] args){
Child t=new Child();
//System.out.println(t.i); /*will not work


[ July 21, 2008: Message edited by: subhasish nag ]

Thanks,<br />Subhasish
Mike Mitchell
Ranch Hand

Joined: May 28, 2008
Posts: 38
Thanks Subhasish.
I agree. Here's the link:
subject: K&B Ch10#8 protected access question
It's not a secret anymore!