简体   繁体   中英

what's the difference between class type variables or instantiating in a constructor/method

public class MotoXCellPhone {

    //assume there's a speaker class
    private BlueToothSpeaker speaker; 

    //why instantiate in constructor?

    MotoXCellPhone() {
        speaker = new BlueToothSpeaker();
    }

    //or if i instantiate in a method?
    public BlueToothSpeaker useSpeaker() {
        speaker = new BlueToothSpeaker();
        return speaker;
    }
}

why would i want to instantiate a class in another class' constructor? i don't fully understand composition yet so i'm fuzzy on the 'why" of everything

If you instantiate it in the method, you'll create a new one each time that method is called. If that doesn't make sense -- if you want one BlueToothSpeaker object to be tied to the MotoXCellPhone object for its lifetime -- then you need to create it (or inject it) in the constructor.

The argument is as follows: if someone else uses your code, they might not call useSpeakser() and thus speakers might be null . Instantiating speakers within the constructor asserts that it will not be null .

实例化MotoXCell时,构造函数将运行并实例化BlueToothSpeaker,而方法仅在被调用时实例化新类。

There are two types of member initialization, each with pros and cons, I'll try to enumerate them:

  1. early-initialization :

    • done when declaring the member, or within the class constructor
    • pros:
      • the created object begins it's lifecycle at the same time as it's "parent", and is available at any time without needing to do any checks
      • in the case of a worker class, the created object can start working right away
    • cons:
      • more CPU/memory used for that object
      • depending on the context the object might never be used
  2. lazy-initialization :

    • done on demand, usually within its getter
    • pros:
      • the object will be created only when firstly needed, thus reduces its CPU/memory usage
      • no context dependent, if the member is not needed at all, it will not be created
    • cons:
      • you will need to always access the member via it's getter within the "parent" class, otherwise you might run into crashes
      • care must be taken when dealing with multithreading (eg a lock must be used), and this has a performance impact

Depending of the implementation of your class you might choose one over another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM