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 protected field 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 "protected field" Watch "protected field" New topic

protected field

Ankit Gareta
Ranch Hand

Joined: Mar 28, 2011
Posts: 67

Hi all,

I am little confused about the inheritance of the protected field.

now i inherited it in different package...

now again in different package

so protected variable is available to the hierarchy of the inheritance tree ...

Thanks in advanced

OCPJP 6 (91%)
Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

Are you sure the code you've shared here is the one you tried to run? It looks like you tried to create a package starting with the word "java" which is not allowed...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Ankit Gareta
Ranch Hand

Joined: Mar 28, 2011
Posts: 67

sorry i made mistake first time.....

so, i changed the question
Alex Theedom
Ranch Hand

Joined: Jan 18, 2012
Posts: 77

Hello Ankit,

In the third code snippet I think you mean to import test2.* rather that test1.*. Anyway, the protected access modifier respects inheritance.

Note that in the following code snippets a compile time error occurs stating that The field Test1.val is not visible.

In the first snippet below the Test4 class is a "neighbour" of the Test3 class and in the second snippet the Test4 class is in a completely different package and therefore cannot access the protected variable.

Alex Theedom - Senior Java Developer (OCPJP/OCPJWCD/Spring Web)
Co-author of Professional Java EE Design Patterns. Blogger at Twitter at @alextheedom
I agree. Here's the link:
subject: protected field
It's not a secret anymore!