Frage

Why we can't use access specifiers for variables declared inside method in a Java Class?

War es hilfreich?

Lösung

Because it doesn't make sense. Variables declared in a method are local to the method; i.e. they can't be accessed outside the method. What would modifying the variable's declaration achieve?

Andere Tipps

It would make no sense to do so.

A local variable (one declared in a method) is only in scope during that method - what would it even mean to declare that as "public" or "protected"? Only code within that method is going to know about it, and it's not like you're going to differentiate between different bits of code within that method to allow some parts to access a variable and others not.

Access modifiers make sense only when you want to control how other classes use it. How would you like to control accessing a variable within a method by using those modifiers? That would sound absolutely silly controlling access of variables within a method, especially when the variable scope is only within the method. Once the method completes, the variable will have no existence. Even if the variables are allocated memory from the heap, still, once the reference is gone, the memory is available for garbage collection.

There is no sense of applying access modifier as the local variable access scope is restricted to the method scope. Hence there is no meaning of applying access modifier.

class Foo{ 
    public void stuff(){
     private String x=2;  //compilation error.
}
}

The above code will not compile if we explicitly apply access modifier.

As per the rules of java whatever the variables declared in the scope of method are not accessible outside, which itself means the variables are themselves private, protected and ofcourse we know its default if none specified. so there is no point in declaring a local variable with above mentioned access modifiers. However , you can still use "final" access modifier for the reason that you don't want it to be changed during the course of the method() because of some processing like unwanted reassignment of value to the variable etc.,

  • Variables that are declared within a method or a block or a constructor are known as Local variables.
  • Local variables are initialized within the method/block and are destroyed once the method/block execution is completed.

So, specifying the access modifiers for those type of variables doesn't make any sense.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top