Bryan
Bryan

Reputation: 87

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

Upvotes: 0

Views: 49

Answers (4)

Cristik
Cristik

Reputation: 32833

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 (e.g. a lock must be used), and this has a performance impact

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

Upvotes: 0

Jhenr
Jhenr

Reputation: 46

The constructor will run and instantiate BlueToothSpeaker right when MotoXCell is instantiated, whereas the method will only instantiate the new class when it is called.

Upvotes: 0

Turing85
Turing85

Reputation: 20185

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.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198171

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.

Upvotes: 1

Related Questions