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 (Retired) The Model-View-Controller Pattern Adding Custom Constructors

luis martinez
luis martinez
2,480 Points

why are we doing mImageId = imageId; when we already did them at the bottom

I don't understand why Ben did this

public Page(int imageId, String text, Choice choice1, Choice choice2){ mImageId = imageId; mText = text; mChoice1 = choice1; mChoice2 = choice2; }

when at the bottom we have done this for the imageId,text etc.

public int getImageId() {return mImageId; } public void setImageId(int id){ mImageId = id; }

1 Answer

Hello,

The below code is the "Constructor" of the class:

public Page(int imageID, String text, Choice choice1, Choice choice2) {
        mImageId = imageID;
        mText = text;
        mChoice1 = choice1;
        mChoice2 = choice2;


    }

This is used only when an object of this class type is instanced. e.g.

Page testPage = new Page(
                        R.mipmap.page1,
                        "hello hello hello",
                        new Choice("Learn Android", 4),
                        new Choice("GiveUp on Android, Learn iOS", 5));

With the above code we have created testPage and an instance of the Page class and have passed in the information required for the parameters. Using those parameters the constructor has assigned them according to the below code:

public Page(int imageID, String text, Choice choice1, Choice choice2) {
        mImageId = imageID;
        mText = text;
        mChoice1 = choice1;
        mChoice2 = choice2;


    }

but what if we want to get the imageId for testPage after initializing it? How do we do that?

That is where the getImageId() method we created comes into play.

we could just say:

testPage.getImageId();

and that will return R.mipmap.page1 the imageId we set in the constructor. If we wanted to update this image id to something else for this object, we could do it like this:

testPage.setImageId(R.mipmap.page3);

that would update the image ID, rather than us having to go down the Constructor route and resetting all the values.

Hopefully that makes it a bit clearer. Let me know if you have a question.

luis martinez
luis martinez
2,480 Points

Thank you. I understand it now.