Global variables in Java

后端 未结 24 1873
青春惊慌失措
青春惊慌失措 2020-11-22 11:56

How do you define Global variables in Java ?

24条回答
  •  无人及你
    2020-11-22 12:37

    To define Global Variable you can make use of static Keyword

    public final class Tools {
      public static int a;
      public static int b;
    }
    

    now you can access a and b from anywhere by calling

    Tools.a;
    Tools.b;
    

    Yoy are right...specially in J2ME... You can avoid NullPointerException by putting inside your MidLet constructor (proggy initialization) this line of code:

    new Tools();
    

    This ensures that Tools will be allocated before any instruction that uses it.

    That's it!

提交回复
热议问题