Static variables in Java for test oObject creator

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;
}

      

}

With static {}, what am I typing? I am assuming that the objects are single as a result. However, if I did the following:

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

      

will man2 be called Jill or Joe?

+2


a source to share


2 answers


Static keyword on fields makes them behave like class instances. There is one instance of an object for the entire class and all instances of the class will share the same. The created static constructor is called when the class is loaded into the JVM. This sets up the static fields of the class. After that, any changes to the static fields are reflected for all instances of the object.



In your example, this means that when the TestObjectCreator class is loaded into the JVM, a person is created and the name is set to "Joe". Then you get that person with the first call to TestObjectCreator.createTestPerson () and change the person's name to "Jill". Since there is only one person for TestObjectCreator, you have now changed the person's name in all cases. So person 2 will be called "Jill".

+2


a source


I can't see your setter method, but it would be Jill if you implemented it correctly.

Your class is not currently fully singleton because it is still possible to make multiple instances of your class. To make your singleton one class, make your constructor private. Then write a static instance of TestObjectCreator and return it via a static factory method.



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

0


a source







All Articles