Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object in a static way

Tags:

java

static

Could anyone explain how Java executes this code? I mean the order of executing each statement.

public class Foo {     boolean flag = sFlag;     static Foo foo = new Foo();     static boolean sFlag = true;      public static void main(String[] args)     {         System.out.println(foo.flag);     } } 

OUTPUT:

false 
like image 728
Eng.Fouad Avatar asked May 16 '12 07:05

Eng.Fouad


People also ask

Can I create object in static method?

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.

How do you make an object static?

Note: To create a static member(block, variable, method, nested class), precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

Can we create object in static method in Java?

You can construct a new object from within a static method and then you can call that object's methods, even if they are not static and even if that object is an instance of the same class. Static methods belong to the class. There is just one of them and they don't need to be constructed.


2 Answers

  • Class initialization starts. Initially, foo is null and sFlag is false
  • The first static variable initializer (foo) runs:
    • A new instance of Foo is created
    • The instance variable initializer for flag executes - currently sFlag is false, so the value of flag is false
  • The second static variable initializer (sFlag) executes, setting the value to true
  • Class initialization completes
  • main runs, printing out foo.flag, which is false

Note that if sFlag were declared to be final it would be treated as a compile-time constant, at which point all references to it would basically be inlined to true, so foo.flag would be true too.

like image 79
Jon Skeet Avatar answered Sep 29 '22 21:09

Jon Skeet


foo is instantiated during the static initialization of the class, and before sFlag was initialized, and the default value of a boolean is false.

  1. The class is loaded
  2. Foo is initialized to the instance

    2.a The instance member flag is initialized to the value of sFlag (false by default)

  3. sFlag is initialized to true

Please refer to JLS §12.4 for more details.

like image 44
MByD Avatar answered Sep 29 '22 19:09

MByD