File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Ch10#8 protected access question

 
Mike Mitchell
Ranch Hand
Posts: 38
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.




Thanks,
Mike

K&B Ch10#8

Given three files:



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

A.

B.

C.

D.

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
Posts: 101
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.AB());
//System.out.println(t.i); /*will not work

*/
}
}



thanks,
subhasish
[ July 21, 2008: Message edited by: subhasish nag ]
 
Mike Mitchell
Ranch Hand
Posts: 38
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Subhasish.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic