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

Nishant Jee
Nishant Jee
844 Points

why are we creating a new page object twice? We can access the methods in Page class if we declare the page object only

Please find the code below for more understanding of my query public class Story {

private Page[] mPages;

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

    mPages[0] = new Page();
    mPages[0].setImageId(R.drawable.page0);

//Page object is created twice as you can see in the code. Please help me understand this.

Thanks

1 Answer

Louis Sankey
Louis Sankey
22,595 Points

Hi Nishanti, I think in the first instance you are creating a new Page array. You could also write it on one line like this: private Page[] mPages = new Page[7]; The 7 is because java arrays are static and when you create them you need to specify how many objects they can hold. But at this point you still do not have any Page objects, you only have an empty array that can potentially hold Page objects. To create a Page object you need the second part. mPages[0] = new Page(); This creates a Page object at the first index of the Page array. Then you can access it and set the attribute by referencing the first index. mPages[0].setImageId(R.drawable.page0); Hope that helps.