Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static protected ( how it works? ) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static protected ( how it works? )" Watch "static protected ( how it works? )" New topic
Author

static protected ( how it works? )

Alexan Kahkejian
Ranch Hand

Joined: Apr 30, 2003
Posts: 74
Hi all
In the case that an instance variable is static protected, can someone explain how it will behave because I tried it but it seems that you can access it from anywhere ( like public ).
example:
// File A.java
package package1;
public class A{
static protected int var;
}
// File B.java
package package2;
import package1;
public class B extends A {
public static void main( String[] args ){
B instance = new B();
var = 10; // Legal OK
instance.var =10; // Legal OK
A parent = new A();
parent.var =10; // Legal WHY??? LINE 6
A.var =10; //Legal WHY??? Line 7
}
}
Can someone explain what happened on lines 6 & 7 and what was the benefit from the protected modifier?
Thanks in advance
Alexan
[ May 16, 2003: Message edited by: Alexan Kahkejian ]
[ May 16, 2003: Message edited by: Alexan Kahkejian ]

Alexan Kahkejian<br />SCJP<br />SCWCD<br /><a href="http://www.javaemployer.com" target="_blank" rel="nofollow">http://www.javaemployer.com</a>
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Welcome to the Ranch Alexan.
The code agrees with JLS 6.6.2.1. JLS mentions that the restrictions you expected to see in line 6 and 7 apply only for instance members.
Regarding JLS 6.6.2:

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.

Given that the static members are shared among all the instances of a class, it seems that all of them are allowed access to a static protected member (*). Are they thought to be "responsible" for the implementation of those members?

(*) As long as access occurs in a subclass of the declaring type.
[ May 16, 2003: Message edited by: Jose Botella ]

SCJP2. Please Indent your code using UBB Code
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static protected ( how it works? )