Skip to content
Advertisement

Optional parameters: Multiple constructors cause errors

Since in Java optional parameters are not possible, I tried to create 2 constructors.

public class Tts {
    public Context context;
    private final MediaPlayer _mediaPlayer;
    private final CopyBarVisualizer _barTop;
    private final CopyBarVisualizer _barBottom;

    public Tts(Context context) {
        this.context = context;
    }

    public Tts(Context context, MediaPlayer _mediaPlayer, BarVisualizer _barTop, BarVisualizer _barBottom) {
        this.context = context;
        this._mediaPlayer = _mediaPlayer;
        this._barTop = (CopyBarVisualizer) _barTop;
        this._barBottom = (CopyBarVisualizer) _barBottom;
    }
}

Now my problems are the private properties. There I get the error

Variable ‘_mediaPlayer’ might not have been initialized

In another method, I want to check if the properties are set. But how can I avoid these errors?

Advertisement

Answer

If you want to solve the error problem, you can fix it with the code below; however, when the constructor initializes final fields, you can’t change them, so probably it’s better to remove the final keyword.

public class Tts {
    public Context context;
    private final MediaPlayer _mediaPlayer; 
    private final CopyBarVisualizer _barTop; 
    private final CopyBarVisualizer _barBottom; 

    public Tts(Context context) {
        this(context, null, null, null); // to solve the error problem
    }

    public Tts(Context context, MediaPlayer _mediaPlayer, BarVisualizer _barTop, BarVisualizer _barBottom) {
        this.context = context;
        this._mediaPlayer = _mediaPlayer;
        this._barTop = (CopyBarVisualizer) _barTop;
        this._barBottom = (CopyBarVisualizer) _barBottom;
    }
}
Advertisement