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

mHits mMisses

Why do we initialize mHits and mMisses in the constructor?

2 Answers

We initialize any members in constructor, because

It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.

If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).

Taken from here: very very nice explanation with example

http://stackoverflow.com/questions/3918578/should-i-initialize-variable-within-constructor-or-outside-constructor

but why do we initialise them in the constructor? we don't have more than 1 constructor

Now I don't understand your question at all...

It is one of the purposes of constructors: to initialize in them members ...

If you initialize member variables somewhere outside constructor, you better have very very significant reasons to do it.... Which I honestly don't know.

Constructor is first of all helpful tool to initialize Class with certain members set.

You can always write

SomeClass someClass = new SomeClass();
someClass.setMember("memberString");

But why?

When you can simply write

SomeClass someClass = new SomeClass("memberString");

We are simply reducing code we write, by using constructors with many arguments, that's it