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 trialMd shujaul Haque
839 PointsConstructor
class SongBook{
private List<Song> mSongs;
public SongBook(){
mSongs = new ArrayList<Song>();
}
public void addSong(Song song){
mSongs.add(song);
}
public int getSongCount(){
return mSongs.size();}
}
why we use constructor for this class and how its work here and benefit of using it here please explain
[MOD - edited code block - srh]
1 Answer
markmneimneh
14,132 PointsHello
regarding your question:
why we use a constructor for this class and how its work here and benefit of using it here please explain
public SongBook(){
mSongs = new ArrayList<Song>();
}
This is the no argument constructor ... and generally speaking, regardless of the language (Java, C#, C++ ... it get created for you whether or not you explicitly add it to the code.
Therefore, you basically get this for free:
public SongBook(){
}
No need to add constructor in your java class. Compiler will provide a default no- arg constructor. If you add a constructor, then this default constructor will not be added. If you dont define constructors in java you get one automatically as simple as that.
now since this constructor is called when instantiating an object. as in :
SongBook mySongBook = new SongBook();
why not make use of the default constructor to start a new collection?
and this is what this code is doing when the SongBook mySongBook = new SongBook(); line is executed.
public SongBook(){
mSongs = new ArrayList<Song>();
}
Md shujaul Haque
839 PointsMd shujaul Haque
839 Pointsthanks a lot its helpful information