开发者

Static variables in Java for a test oObject creator

开发者 https://www.devze.com 2022-12-30 08:58 出处:网络
I have something like the following TestObjectCreator{ private static Person person; private static Company company;

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 开发者_如何学PythonJoe?


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".


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号