• Post Reply Bookmark Topic Watch Topic
  • New Topic

quick modifier question  RSS feed

 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how come this is legal



and this is not,to my surprise I got an illegal use of modifier error




Thanks
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simply, access modifiers do not get applied to local variables. It is simply not allowed -- as it is always private to the block where it is declared.

Henry
 
Yosuf Ibrahim
Ranch Hand
Posts: 128
4
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adam Chalkley wrote:how come this is legal



and this is not,to my surprise I got an illegal use of modifier error




Thanks


When you declare a variable inside a method you are basically telling the computer I will only use this within this method, therefore you are not required to use access modifiers because you cannot use it anywhere else. Outside the methods though when you are creating instance variables those variables can be accessed by the class and other classes. Basically, everyone knows about them. Using access modifiers in that case you are telling the compiler to limit the access to those variables.
private (only the class they have been created in can see them)
public (everyone can see them)
protected (classes in the same package and subclasses only can access)


In other words, the compiler knows that the variable declared inside a method is only for the desired method, when you place an access modifier it gets confused about how can others access this variable.

Cheers
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!