views:

57

answers:

2

Hey,

I have something like the following

TestObjectCreator{

    private static Person person;

    private static Company company;

static {
    person = new Person()
    person.setName("Joe");
    company = new Company();
    company.setName("Apple");
}

public Person createTestPerson(){
    return person;
}

 public Person createTestCompany(){
    return company;
}

}

By applying static{} what am I gaining? I assume the objects are singletons as a result. However, if I did the following:

  Person person = TestObjectCreator.createTestPerson();
  person.setName("Jill");
  Person person2 = TestObjectCreator.createTestPerson();

would person2 be named Jill or Joe?

A: 

I can't see your setter method, but it would be Jill, in case you've implemented it properly.

Currently your class is not completely a singleton because it is still possible to make several instance of your class. In order to make your class singleton, make your constructor private. Then, write a static instance of TestObjectCreator and return it through a static factory method.

The advantage you get by making Person and Company static are that, all the instances of the TestObjectCreator would have the same copy of Person and Company. I'm not sure if that is what you want, but it is what static provides you.

Snehal
+2  A: 

The static keyword on fields causes them to behave as class instances. There is one copy of the object for the entire class, and all instances of the class will share the same one. The static constructor you have created is called when the class is loaded into the JVM. This sets up the static fields of the class. After this, any changes to the static fields is reflected for all instances of the object.

In your example, this means that when the TestObjectCreator class is loaded into the JVM, the person is created and name set to "Joe". You then retrieve this person with the first TestObjectCreator.createTestPerson() call, and change the name of the person to "Jill". Since there is only one person for TestObjectCreator, you have now changed the name of the person in all cases. So, person 2 would be name "Jill".

Zoe Gagnon
Thanks, that's what I was looking for! I'll give you the answer point when I can.
stevebot
No problem! The static keyword is one of the more confusing points of Java. I'm really happy I could help you clear it up.
Zoe Gagnon