Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired 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); }

1 Answer

Yanuar Prakoso
Yanuar Prakoso
15,196 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.