-2

I recently wrote code like this:

class Test{
  public int a;
  public int b;
  public void demo(){
    //public int c;
    final int d;
  }
}

Commented code can not be compiled. I always thought that the argument can be public,like b, but why not c?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
shonminh
  • 158
  • 1
  • 2
  • 13

5 Answers5

4

public int c is an error since local variables are only visible to the method in which they are declared, so there's no meaning to access modifiers.

As for final int b, I didn't notice you are assigning 0 to it. It should be fine. The problem may have been that you had two variables named b (assuming the commented line doesn't replace the uncommented b declaration).

Eran
  • 387,369
  • 54
  • 702
  • 768
2

Visibility modifiers like public describe if some element or type can be accessed from other type. They can be applied to

  • type (class, interface, enums)
  • and top level elements of types like
    • fields,
    • methods,
    • constructors,
    • inner-types.

Using access modifier with local variables like c doesn't make sense since local variables can be seen only in local scope (in {...} scope they ware declared - in your case inside demo method), so you can't limit nor increase that visibility range.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

In combination with variables public shows the acceslevel to this specific variable in a class. SO about public-private-protected

You are trying to define a variable public inside a method, this will throw an error, since this variable is only locally accessible inside this method and therefore the wouldn´t have any usefull meaning.

The other error is generated due to a missing decleration of the class variable, which is needed when using the keyword final.

Community
  • 1
  • 1
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
1

Only class variable can have access modifiers like private or public. So you cannot have final variable inside demo() method.

For final int b=0, you have already defined it.

Renjith
  • 3,274
  • 19
  • 39
0

Here one of four fundamental concept of OOP come in role it is Encapsulation.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the scop of it

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class.

In case of your code you said, argument can be public,like b but why not c. It is because scope the c is only for method demo() and it will accessible only within it. Same is applicable for final.