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 Efficiency! Building the Model

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Why we always use constructor?

Dear community,

in the video "Building the Model", why we canΒ΄t declare and initialise the mSongs variable this way?

public class SongBook {
List<Song> mSongs = new ArrayList<Song>();
}

Why we have to declare the mSongs in the SongBook classs and initialise the same mSongs in the constructor of the SongBook class???

I hope you understand my question ...

:)

1 Answer

Dennis Ping
Dennis Ping
1,398 Points

Hopefully my explanation isn't too hectic.

So, you just made a brand new class: SongBook. You need a SongBook constructor to even be able to instantiate it anywhere else. That's the rule. Think of a constructor like the instructions to build something.

Things like int, String, boolean don't need a constructor because these are primitive variables already built into Java. However, "SongBook" is clearly not built in. You created it ... so now you need a constructor in order to "make it exist." Without a constructor, you wouldn't be able to use SongBook in another class.

For example, if you created a SongMixer class (which remixes 2 songs together) you would use a constructor to instantiate SongBook in your SongMixer class.

Usually, you make a constructor method right after you declare your class.

public class MyCustomClass {
   public MyCustomClass() {
      //This is the constructor
      //Insert instructions on how to build MyCustomClass
      //This will allow you to instantiate MyCustomClass in other places
   }

   //Do other things here if you have to.
}