1

If I were to do something such as:

public class Game
{
    private boolean RUNNING = true;

    Game()
    {
    }

    public static void main(String[] args)
    {
        Game game = new Game();
    }
}

At what point in time would RUNNING = true?

edit: for clarity, at what point in the program would running be set to true. ex: Before the constructor, after the constructor, etc.

Lemmons
  • 1,738
  • 4
  • 23
  • 33

5 Answers5

4

It will be set to true before the constructor. You can use it in the constructor as true.

mwerschy
  • 1,698
  • 1
  • 15
  • 26
1

This code explains itself:

public class SuperClass
{
    String superField = getString("superField");

    public SuperClass()
    {
        System.out.println("SuperClass()");
    }

    public static String getString(String fieldName)
    {
        System.out.println(fieldName + " is set");
        return "";
    }

    public static void main(String[] args)
    {
        new ChildClass();
    }
}

class ChildClass extends SuperClass
{
    String childField = getString("childField");

    public ChildClass()
    {
        System.out.println("ChildClass()");
    }
}

OUTPUT:

superField is set
SuperClass()
childField is set
ChildClass()
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0
private boolean RUNNING = true;
Game() {
}

is exactly the same as

private boolean RUNNING;
Game() {
    RUNNING = true;
}

Actually, the comiler will move the initialization at the beginning of the constructor. The value will then be set when instantiating an object of that class.

sp00m
  • 47,968
  • 31
  • 142
  • 252
0

When the constructor is called using the new operator all non-static members of the class are initialized before the code inside the constructor is executed. You can use the debugger and step into that call and see where it goes first. Static members are initialized when the class is loaded and for the first time accessed (see this question for more detailed info about static members).

Community
  • 1
  • 1
A4L
  • 17,353
  • 6
  • 49
  • 70
0

When you try to use local variables which not manually initialized, you will get a compile time error.

public static void main(String args[]){
               int a;
              System.out.pritnln(a); //error
      }

But it's not the case with instance variables. This itself shows that they are ready for usage before the constructor even.

   public class Example{
            private int a;
            public Example(){
                   System.out.println(a);   //No error
            }
            public int getA(){
                   return a;           //No error
            }
   }

I hope this intuition answers your question..........

pinkpanther
  • 4,770
  • 2
  • 38
  • 62