• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static protected ( how it works? )

 
Alexan Kahkejian
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jose Botella
Ranch Hand
Posts: 2120
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic