2

Quick question about the code below:

public class Test {

    public final static Test t1 = new Test("test 1");
    public final static Test t2 = new Test("test 2");
    public final static Test t3 = new Test("test 3");

    private String s;

    private Test (string s1) {
        s = s1;
    }
}

I am confused as to whether this code will create unlimited instances of itself?

Pectus Excavatum
  • 3,593
  • 16
  • 47
  • 68
  • 1
    I suggest that you look at these answers as well. http://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-java – Joel Mar 12 '13 at 14:22

5 Answers5

3

No the VM will not: "create unlimited instances of itself."

Your static fields (t1, t2 and t3) will be created once (each) on Class level, and not on Instance level. Your 3 fields will be shared between all instances.

Frank
  • 16,476
  • 7
  • 38
  • 51
1

The code will not create unlimited instances of itself because the variables t1, t2 and t3 are initialized statically (meaning once when the class gets loaded, not once for each instance), because of the static declaration in combination with the assignment in the declaration.

You may want to read up on what exactly static does.

Useful note:

The below example, on the other hand, while using a static variable, would cause it to be initialized when an instance gets created (because of the assignment in the constructor) and would thus cause a StackOverflowError:

public class Test {
   static Test t1;
   Test () {
      t1 = new Test();
   }
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
1

static members are not part of the created object. So there will be no infinite creation of Test objects.

uba
  • 2,012
  • 18
  • 21
0

You're asking it because the static (t1, t2 and t3) declarations give you the impression that each instance will have their own copies of these variables.

Actually, this is not what will happen. Static variables are not created per instance. Only one instance of them ever exists in a JVM.

Filipe Fedalto
  • 2,540
  • 1
  • 18
  • 21
0

If it would have been something like

public class Test {
   // no static so these are created for each instance of A or each time constructor is called
   public final Test t1 = new Test("test 1");
   public final Test t2 = new Test("test 2");
   public final Test t3 = new Test("test 3");

   private String s;

   private Test (string s1){
      s = s1
   }

}

Then it would have created unlimited instances as t1,t2 and t3 are instance level variables.

But in your case they are static so instances are created on class loading time and not with each instance so no unlimited instances.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120