0

Is there an easy way to make a group of variables in a class as public. For example to make a group of variables as static, I can use something like below.

class A {
    static {
        int x;
        int y;
    }
}

Is there a way to do something similar to make the variables as public. Something like this.

public {
        int x;
        int y;
        }

Edit:

I understood that the static block doesn't do what I supposed it will do. What I need is a java version of something like this in C++

 class A {
      public:
          int x;
          int y;
  }
Rockstar
  • 2,228
  • 3
  • 20
  • 39
Alex
  • 1,178
  • 3
  • 9
  • 24
  • 2
    I don't think that `static { ... }` code does what you think it does. See [Static initialization blocks](http://stackoverflow.com/questions/2420389/static-initialization-blocks) – William Price Dec 15 '14 at 07:00
  • The Java approach of requiring explicit declaration of public access for each variable actually makes code less prone to errors from moving variables around inside the class definition accidentally changing their access level. Also in C++ one sometimes has to scroll the page to see if a variable is private/public etc... Maybe just try to think of the Java approach as a "feature". – Matt Coubrough Dec 15 '14 at 07:09

4 Answers4

5

Your code sample doesn't make a group of variables static, it declares local variables in a static initialization block.

You'll have to declare each variable as public separately.

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

The above code declares a static initialization block which is not same as declaring the variables as static. (More info.)

For the problem at hand you have to declare variables public separately.

nitishagar
  • 9,038
  • 3
  • 28
  • 40
0

You could use public int x,y. And be careful about static {} blocks.

Everv0id
  • 1,862
  • 3
  • 25
  • 47
0
static int x,y,z;

This should make a group of variables static... as long as they are of the same type of course. You can also make them all public, private etc.

public static int x,y,z;
Ubica
  • 1,011
  • 2
  • 8
  • 18