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

Alok Singh
PRO
Alok Singh
Pro 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,118 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
25,418 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.