Java Java Data Structures Efficiency! Building the Model

Andre Kucharzyk
Andre Kucharzyk
4,479 Points

Why use constructor without parameters?

In SongBook,java lecturer introduced constructor without parameters. Why? What's the reason behind that?

package com.teamtreehouse.model;

import java.util.ArrayList; import java.util.List;

public class SongBook { private List<Song> songs;

public SongBook(){
    songs = new ArrayList<Song>();     <--------- this 
}

public void addSong(Song song) {
    songs.add(song);
}

}

Couldnt we add songs = new ArrayList<Song>(); to the addSong method like that?

public void addSong(Song song) { songs = new ArrayList<Song>(); songs.add(song); }

Yanuar Prakoso
Yanuar Prakoso
14,816 Points

yes it might be done. But the main reason why Craig put it in the constructor is because the ArrayList of Song can be initialized every time a user create a new SongBook object. Therefore the ArrayList will be used in more methods than just add methods. That is I think the main reason why he put it in the constructor not in the add method.