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

Android Build an Interactive Story App The Model-View-Presenter Pattern Adding Custom Constructors

Alok Singh
PLUS
Alok Singh
Courses Plus Student 3,397 Points

If we don't initialize the page array object inside the constructor it shows an error, why is that?

public class Story { private Page[] pages;

public Story(){
    pages = new Page[7];
}

pages[1] = new Page(R.drawable.page1,
                    R.string.page1,
   new Choice(R.string.page1_choice1, 3),
   new Choice(R.string.page1_choice2, 4));

pages[2] = new Page(R.drawable.page2,
                    R.string.page2,
   new Choice(R.string.page2_choice1, 4),
   new Choice(R.string.page2_choice2, 6));

pages[3] = new Page(R.drawable.page3,
                    R.string.page3,
   new Choice(R.string.page3_choice1, 4),
   new Choice(R.string.page3_choice2, 5));

pages[4] = new Page(R.drawable.page4,
                    R.string.page4,
   new Choice(R.string.page4_choice1, 5),
   new Choice(R.string.page4_choice2, 6));

pages[5] = new Page(R.drawable.page5, R.string.page5);

pages[6] = new Page(R.drawable.page6, R.string.page6);

}

2 Answers

Joshua Douce
Joshua Douce
13,120 Points

Because when you are outside the constructor the compiler is expecting a method or you can declare public and private member variables they do not have to be at the top of the class but as you are initializing each position in the array the compiler does not understand what you are trying to do.

If you wanted to initialize all the value outside of the constructor you could do it one long initialization when you declare your private member field. Or alternatively, you could have a method such as

private void populateArrayWithData(){ enter data here }

or as here it is done in the constructor.

Alan Kuo
Alan Kuo
7,697 Points

still have no idea why after we created an array of pages we can't start assigning each index outside of the constructor.

alastair cooper
alastair cooper
30,617 Points

When an array is declared, only a reference of array is created. To actually create or give memory to array, you need to initialise it. Constructor is the best place so you can be sure any method calls after that can use it.