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 Creating the Story

Jian Chen
Jian Chen
4,938 Points

What is so special about an instance variable?

So people make an instance variable like this, Class variable = new class. But what is the difference from just declaring it as, Class variable = somevalue ? Don't they both have the same method and states because they both belong to the same class?

2 Answers

Hi Jian,

The convention doesn't work quite as you think in that example.

An instance of a class requires building, otherwise knows as constructing. Take the Story class in this video as an example.

You can create the variable, like you say, Story myStory; does that. But this doesn't fill the instance with anything. I guess it just reserves a Story sized chunk of memory, but leaves it blank.

You then assign the contents of a Story instance by calling the class constructor. This creates an actual instance, depending on the constructor you have created and any parameters it takes. So, new Story() creates a real instance of a Story but that has no name, or anywhere to live in memory. Hence, you assign it to the chunk of memory named myStory by completing the instantiation and assignment such as:

Story myStory = new Story();

I hope that makes sense. It probably isn't wholly technically correct but it's my best shot!

Shout if you need anything more.

Cheers,

Steve.

Jian Chen
Jian Chen
4,938 Points

Thank you Steve, I really appreciate your help and you did clarify to me what "new" does. Do you know why we don't create an instance for the String class, as we usually just write ' String variable = "someChar"; ' and not as ' String variable = new String then ' variable = "someChar" '?'

I think the built-in class types like String do the heavy lifting behind the scenes. The code is there, we just don't see it.

I've never tried doing that, either - might be an interesting experiment!

Steve.

Tried it, and you get a warning about not needing to use the constructor.

Jian Chen
Jian Chen
4,938 Points

Thank you, Steve. I understand it now.