This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusing 'protected' behavior Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confusing Watch "Confusing New topic
Author

Confusing 'protected' behavior

Maduranga Liyanage
Ranch Hand

Joined: May 25, 2005
Posts: 124
Now this is something I didn't come across in the text book.

Why is the behavior of protected variables different for static and non-static variables?

For example:
package packageA;
public class pack
{
static public int x1 = 7;
static protected int x2 = 8;
public int x3=9;
protected int x4 =10;
}


import packageA.pack;
class test extends pack
{
public static void main( String args[] )
{
pack p = new pack();
System.out.println( p.x1 );
System.out.println( p.x2 );
System.out.println( p.x3 );
System.out.println( p.x4 );
}
}


I get:
test.java:10: x4 has protected access in packageA.pack
System.out.println( p.x4 );


Now I must have missed something with grave importance here.
From my understanding:
1) Protected: Classes in the same package (extended or not) and classes in other packages (extended) can access them.
2) Default: Classes in the same package (extended or not) can access but not any class in any other package.

So what is this distinction that applies to static variables.
And from the code above, it seems that even by extending the class, I cannot access the protected non-static member? and seems the behavior I mentioned above only applies to static variables?

An explanation is greatly appreciated.

Cheers.
Vijay Raj
Ranch Hand

Joined: Oct 10, 2005
Posts: 110
Hi Maduranga,

A subclass outside the package cannot access a protected member by using a reference to a superclass instance.

Try doing



Regards,
Vijay.
Morteza Manavi-Parast
Ranch Hand

Joined: Dec 25, 2008
Posts: 66
That's right. A subclass in another package can only access protected members in the superclass via references of its own type or it supertypes. So obviously using a reference type of subclass will solve the problem. Note that the "type of the reference variable" is important and not its actual object type stored in that reference. e.g. this will not work too:

pack p = new test();

Since compiler check the reference type and not the actual object type.

We all know these stuff and it's all true, BUT! What really bugs me in this case is why access to the STATIC PROTECTED FIELD in super class works via a reference type of super class in subclass?? I mean why this works:

System.out.println( p.x2 );

again x2 is protected and p is a reference type of the superclass pack and we run this in the subclass test. So why this works?

Any ideas?





SCJP 6
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Morteza Manavi-Parast wrote:That's right. A subclass in another package can only access protected members in the superclass via references of its own type or it supertypes. So obviously using a reference type of subclass will solve the problem. Note that the "type of the reference variable" is important and not its actual object type stored in that reference. e.g. this will not work too:

pack p = new test();

Since compiler check the reference type and not the actual object type.

We all know these stuff and it's all true, BUT! What really bugs me in this case is why access to the STATIC PROTECTED FIELD in super class works via a reference type of super class in subclass?? I mean why this works:

System.out.println( p.x2 );

again x2 is protected and p is a reference type of the superclass pack and we run this in the subclass test. So why this works?

Any ideas?





Because p.x2 is just syntax for pack.x2.


All code in my posts, unless a source is explicitly mentioned, is my own.
Morteza Manavi-Parast
Ranch Hand

Joined: Dec 25, 2008
Posts: 66
Thanks and Why we can access a protected member in another class, out of its package, via the super class type?
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Morteza Manavi-Parast wrote:Thanks and Why we can access a protected member in another class, out of its package, via the super class type?

This is from the JLS:

6.6.2.1 Access to a protected Member
Let C be the class in which a protected member m is declared. Access is permit-
ted only within the body of a subclass S of C. In addition, if Id denotes an
instance field or instance method, then:
• If the access is by a qualified name Q .Id , where Q is an ExpressionName,
then the access is permitted if and only if the type of the expression Q is S or a
subclass of S .
• If the access is by a field access expression E .Id , where E is a Primary
expression, or by a method invocation expression E .Id(. . .), where E is a
Primary expression, then the access is permitted if and only if the type of E is
S or a subclass of S .


Notice that the restrictions placed on instance member access are not a problem for static member access.
Maduranga Liyanage
Ranch Hand

Joined: May 25, 2005
Posts: 124
Thank you very much guys. phew! there are many intricate details to keep in mind.

So basically;
To access a protected static member (different package):
A. MUST extend the class
B. can access through super class instance/ref and subclass instance

To access a protected non-static member (different package):
A. MUST extend the class
B. ONLY be accessed through a subclass object.
C. CANNOT access through a superclass object.

To access a protected static/non-static member (same package):
A. does NOT need to extend the class
B. can be accessed through superclass instance/reference(for static) and subclass instance.


And for DEFAULT members, they must be in the same package, and everything related to protected (same package) applies here.

This is what I found from running some code. Did I miss something?

Thank you for all the help guys.
Morteza Manavi-Parast
Ranch Hand

Joined: Dec 25, 2008
Posts: 66
Perfect. Thanks Ruben for clearing my doubt (and also implicitly gave me a definite resource to clear the doubts!) and also thanks Maduranga for classifying the inferred concept in such a nice way!

P.S. There are lots of critical concepts like this that usually missed in SCJP study guide books and I wish this forum had a Wiki so that we could put these concepts in there and make it available for everybody's references. That's unfortunate that soon this point also will be buried and lost under thousand of future posts...
Maduranga Liyanage
Ranch Hand

Joined: May 25, 2005
Posts: 124
Yes Morteza..
I studied the K&B (both study guide and Head First) and while they do a really good job in discussing the important points, there are some minute details like this that are missed, and only come across from various other sources...
It would be great to have a WIki for this kind of concepts...
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Morteza Manavi-Parast wrote:Perfect. Thanks Ruben for clearing my doubt (and also implicitly gave me a definite resource to clear the doubts!) and also thanks Maduranga for classifying the inferred concept in such a nice way!

P.S. There are lots of critical concepts like this that usually missed in SCJP study guide books and I wish this forum had a Wiki so that we could put these concepts in there and make it available for everybody's references. That's unfortunate that soon this point also will be buried and lost under thousand of future posts...

No problem Morteza! Yep, there is quite a number of details. To be fair, no book could completely cover all possible details. The closest you can get is the JLS, but because of its strictness and comprehensive nature it is not a very approachable source in some ways.
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Maduranga Liyanage wrote:Yes Morteza..
I studied the K&B (both study guide and Head First) and while they do a really good job in discussing the important points, there are some minute details like this that are missed, and only come across from various other sources...
It would be great to have a WIki for this kind of concepts...

Maduranga, the Wiki thing might sound like a good idea at first, until you realize that there are potentially thousands of obscure details that it would need to cover. I think the K&B book does a great job of getting you ready for the exam, but if you think you need to complement it with something, I would suggest the JLS along with this forum.
Maduranga Liyanage
Ranch Hand

Joined: May 25, 2005
Posts: 124
Thank you Ruben. Yes the K&B is pretty wonderful. also I didnt have much problems doing the questions came with the CD. Until I started to do John Meyers' Inquisition questions where I ran into lot of very minute details. Now I am not sure if K&B questions is the level of the real exam or whether it is simpler than the real thing.. but I found lot of small things I didnt know with the Inquisition. Going to try Devaka's afterwards...
Morteza Manavi-Parast
Ranch Hand

Joined: Dec 25, 2008
Posts: 66
Yes, that's right and that's exactly the reason for having a Wiki to cover all those thousand things in a categorized way based on the exam objectives.

And one more thing, I did not want to particularly name any specific resource but now that you did it, I cannot help but add a few more points in here:
In my opinion the K&B book did a great job on simplifying the concepts and creating an interactive and live material for the readers, BUT there are lots of crucial points exists which are silently ignored (or missed) in that book. I'm talking about the points exactly in the range of exam objectives, nothing else. To prove that, You just name any of the concepts in SCJP exam and I will provide you with at least one example of those ignored (or missed doesn't matter) points in the K&B book. And here is why the Wiki idea turns out to be indispensable: A place to gather all of those missed points for everyone's references!


Maduranga, it's a good idea, give Devaka's questions a try and you'll learn more about what am I talking about...
Maduranga Liyanage
Ranch Hand

Joined: May 25, 2005
Posts: 124
Thank you Morteza.
Actually I am keeping (rather saving) Devaka's as my last one before the exam because everybody seems to find it very hard or rather tricky..
I was happy with K&B and doing the practice questions included in the CD. Reading Amazon reviews people have mentioned that they passed SCJP just on the book.. so I was pretty happy and confident (I have already done SCJP 1.4 some years ago but SCJP 5 is miles apart from it).. anyway when I started doing John Meyers, I was suprised.. I kept getting wrong answers continuously for which I was confident that I was right.. it was because those questions test on very small tricky parts, which the K&B did not test... now I am confused as to whether the real exam will be much closer to Inquisition question or K&B questions... because with Inquisition questions, I don't want to chose any answer other than a 'compilation error'.. because there is almost always some very tiny thing that will give a compilation error... I think you know what I mean...

After finishing SCJP (and if I pass) I might give a go at preparing small notes to complement the K&B.. I am not taking anything away from it.. it is a wonderful book and I think it is practically impossible to explain every little thing in Java.. but maybe I expected a little tougher question from the companion CD...
Morteza Manavi-Parast
Ranch Hand

Joined: Dec 25, 2008
Posts: 66
Reading Amazon reviews people have mentioned that they passed SCJP just on the book..

I am not agree with this. I think if somebody rely solely on this book and its CD, then he should start a topic like "How to effectively fail the SCJP..." right after his exam in here! I think those people passed the exam by reading this book and ALSO do a lot of mock exams and those mocks cover the missed concepts. Please note that I am talking about persons without Java experience eager to pass the SCJP and not experienced Java developers which came across those concepts through hands on experiences before....

I think it is practically impossible to explain every little thing in Java..

I am not totally agree with this one too. Yes It's a fact that it's impossible to cover every tiny subtle point in a book BUT there are some obvious concepts missed in that book which shouldn't be. (again examples are available if you are interested). Of course I don't want to take anything away from it too, as I told they did a great job on writing a interactive and easy to understand material, but I think it still has rooms for improvement.

And the last thing is I am also thinking of creating an onine reference for the important missed concepts but not after my exam, in the same time I am getting prepare for it...


Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Morteza,

I think you have lost perspective on what the SCJP exam is. I think the SCJP exam is a tool for learning that will help you understand 90% of the most used constructs of the language. Because of the amazing number of little details that go into any programming language, it would be impossible to learn any little detail. Not only that, but it would be undesirable and counterproductive to learn all those little details. The only people that should be learning those details as far as I am concerned is the language implementors and compiler developers. In the workplace what you need is a solid understanding of the language that will help you to be productive. If you run into a problem that has to do with an arcane feature of the language, or a little detail that you don't remember, what you do is search in Google, or consult the JLS.

And I think it is perfectly possible to pass the exam using only the K&B book, but you must understand and grasp the book completely. Furthermore, no source is self contained, and you are always free to expand your knowledge using alternate sources. I would be hard pressed to offer any suggestions to Kathy and Bert to make the book better. It is that good a tool for its intended purpose.
Morteza Manavi-Parast
Ranch Hand

Joined: Dec 25, 2008
Posts: 66
Ok, I don't like abstract discussions, so I provide you with an example in the below link (I post it in a separate thread cause it's pretty long and I do not want to messed up here)

FYI - Subclassing from an Inner Class

So, can you please let me know that in your "perspective", is the above link is one of those "Fancy_tricky_concept_only_language_designers_ should_know_about" or is just another crucial point in the exam objectives that someone might be encountered with a real question out of it on the real exam?

Maduranga,
There you go, please read the above thread and let me know if you have any questions.

Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Morteza Manavi-Parast wrote:Ok, I don't like abstract discussions, so I provide you with an example in the below link (I post it in a separate thread cause it's pretty long and I do not want to messed up here)

FYI - Subclassing from an Inner Class

So, can you please let me know that in your "perspective", is the above link is one of those "Fancy_tricky_concept_only_language_designers_ should_know_about" or is just another crucial point in the exam objectives that someone might be encountered with a real question out of it on the real exam?

Maduranga,
There you go, please read the above thread and let me know if you have any questions.


In my "perspective" you can't expect a book to include all possible details. Even the JLS doesn't cover the exam fully. I'm not saying that discussing these details is worthless. But to put down a book because it doesn't contain all possible details is quite unfair. Think about it in terms of the law of diminishing returns: You might spend 2 months learning a number of concepts that will get you on average 85% on the exam. To ensure that you get to 97% on the exam with a certain degree of probability you might have to spend another 20 months. Do you think that is practical?

No book is perfect, but the K&B is better than most, and does a great job at doing what its purpose is, which is getting you prepared for the SCJP exam.

And I must say I still don't get your point. What is your point again?
Morteza Manavi-Parast
Ranch Hand

Joined: Dec 25, 2008
Posts: 66
In my "perspective" you can't expect a book to include all possible details. Even the JLS doesn't cover the exam fully. I'm not saying that discussing these details is worthless.

Ok, you did not answer my question explicitly but from the above implicit sentences I conclude that you admit this point is not trivial yet is in the exam objectives and of course it's not covered in the K&B. And that's exactly my point: there are a few concepts like this exist that it's uncovered.

But to put down a book because it doesn't contain all possible details is quite unfair.

Who did that? Have you ever read my comments at least once? If you do that, you'll see I never put it down, on the contrary, I talk very high about it. Look, criticizing and mentioning the strong and weak point about something does not mean that we put that thing down!

... and does a great job at doing what its purpose is, which is getting you prepared for the SCJP exam.

I have not written my exam yet so I do not have any argument with you about this one. If you don't either, you can not say the above too. What I have seen and access to is the exam objectives and that's why I can say what is covered and what is not based on the objectives. If the authors ignored those concepts because they already know that those concepts would not appear in the real exam, nevertheless they are part of the standard objectives, then it's a whole different story...

And I must say I still don't get your point. What is your point again?

If you mean the one I mentioned in the other post, then you can put your question there (and not here) and I will clear your doubt about it in there as well.


Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
I don't want to get into a debating war here. Like I said before, I think it is perfectly possible to pass the exam based solely on the book, as long as you understand all the concepts explained in the book. You said that doing that is a sure way to fail the exam, which in my "perspective" is unfair.

I don't recommend only following the book, because you can always benefit from other sources (like this forum, the JLS, and various mock exams.) But I bet many people simply read the book and passed, which is a testament to the quality of that book.

What you did in that other thread is explain some corner cases related to inner classes and inheritance (and all the cases that you explain derive from the fact that an object of an inner class must be tied to an object of the enclosing class, which is clearly discussed in the book.) But that doesn't mean the book didn't cover inner classes and inheritance. The book can't cover all corner cases, and that's my point. You also failed to cover some ramifications of your test cases (like the fact that objects of any subclass of a non-serializable class that extends an inner class would fail to be serializable.) And I bet you could continue coming up with corner cases (nothing wrong with that.) My point is that you are saying that the book did not cover those concepts satisfactorily, and I disagree. If by satisfactorily you mean completely, then you better start to spend the next couple of years doing nothing but finding corner cases. And even then I bet you would miss more than you would find.

I hope this clears my "perspective."
Morteza Manavi-Parast
Ranch Hand

Joined: Dec 25, 2008
Posts: 66
Again, if there is a possibility of having a question based on my example on the real exam, then it is a testament to that this book, solely, is not enough to pass the exam. And I don’t buy that slogan about “I bet many people simply read the book and passed…” either, unless, a real person comes up and says: hey, I, without any java experience, without doing any mocks, just read that book and pass the exam…

And yes, of course the book also covered polymorphism and encapsulation in addition to inner classes and inheritance but it’s not covered that point. And since when a “Syntax” thing becomes a corner case in a programming language?! Furthermore, I don’t care if it’s a core or corner case, I only do care if there is possibility that it will appear on the exam or not, cause in the real exam all the questions have the same value and you don’t score based on the “corner degree” of the questions you have answered.

And one more thing, I don’t care about any of these cases at all, some of them even might be overkill in the real projects. (like one of the fellows asked me on that thread that so why would we do that? What is the design issue behind that?)
I’m concerned only because I don’t want to be surprised in the exam by some new syntax or points I have never seen before. And of course if it takes couple of years to finding all those cases to pass my SCJP, then you make sure that I’ll do that, because it is still better than to stick with one book and treat it like the bible and then getting surprised in the real exam afterwards.
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Morteza,

I think you need to relax a bit. You are putting too much importance into the exam. It seems you are trying to cover all possible different questions that might come up in the exam, and that is not only impractical, but also utterly unrealistic.
Java is a complex issue with many different details, and interrelations and subtleties abound. You can't possibly cover everything, it is simply impossible no matter how long you take trying to do it. You will eventually become frustrated and tired.

I am like you, I like to find answers to questions, and to know how things work. But I think you need to realize that the SCJP exam is not going to make you a Java guru. The exam is there to show that you have a solid understanding of Java's most used features.

You seem to be misinterpreting my words. When I said that it is possible to pass the exam using uniquely the K&B book, I don't mean that it is enough to read the book a few times. You need to fully understand all concepts in the book. Even the authors recommend that you do a lot of coding, because that is the very best single way to fully learn a programming language. So I'm not discouraging anyone from coding, taking practice mock exams, reading the JLS, and visiting this forum. But if I had one single source to prepare for the exam in a limited amount of time, I would definitely choose K&B. It excels at is purpose, which is a to be a guide for those who intend to take the exam. You want it to be a repository of all potential questions that may be in the exam, and that is completely unrealistic. If you fully understand all the concepts explained in the book, then you should be able to work your way through questions in the exam that, while not directly explained in the book, can be however derived from those concepts.

You sounded very negative about the book, and I'm sorry but I had to defend it. The book is what the authors intended it to be, and the vast majority of people agree that it excels at that purpose (it suffices to read any number of Amazon reviews, or the feedback from members of this forum.) You have your right to be displeased with it, but I think you seriously need to question what you expect from the SCJP, and how you are going to prioritize your preparation for it. You simply can't cover all potential questions, it can't be done.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confusing 'protected' behavior
 
Similar Threads
Doubts on Protected Members
Kindly explain this code from SCJP faq
Protected
Protected Modifier Question
A question regarding the protected member access