• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variables and protected access in a different package

 
Simran Dass
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Its not possible to access a protected instance variable in another package using the upreclass object. For e.g in the foll code line 3 gives Compiler ERROR. But why do not the lines 2 and 3 give any compiler error


 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because "y" has "default" access specifier, and default can be seen in the package only. Its package only access specifier.
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simran Dass wrote:Its not possible to access a protected instance variable in another package using the upreclass object. But why do not the lines 2 and 3 give any compiler error[/color]

First, protected can be accessed into the sub class having different package and what you've illustrated with the example is the access of "static" (class) variable and not its protected behavior.
 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
protected members when used by subclasses in different packages, should be accessed through inheritence only. there is no other way to access protected members in different package.
that's why line 3 gives error.


But why do not the lines 2 and 3 give any compiler error


I guess you meant line 1 and 2.

Here you are accessing a static member which can be accessed by either class name or class reference irrespective of package provided class is public.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think, Your question is wrong.......

The line 3 is only making trouble. Because, It's accessing the protected member of Class of different package. For a subclass outside the package, the protected member can be accessed only through inheritance.

In line 1, The compiler will changed that line after compiling to as line 2. And here static is dominating.......
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic