Bummer! You must be logged in to access this page.

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

new constructor

in the Build a Simple Android App section, on the example, in the MainActivity, we have to declare the objects:

private FactBook mFactBook = new FactBook(); private ColorWheel mColorWheel = new ColorWheel();

Why can`t we just write private ColorWheel mColorWheel; ? I noticed that even if we only declare it as private ColorWheel mColorWheel = new ColorWheel(); we can still use its method below, in the onCreate which is "String fact = mFactBook.getFact();"

When do we create a variable using the "new" constructor and when it is not needed?

2 Answers

If you were to change your declaration of mColorWheel to private ColorWheel mColorWheel; and then tried to use it's method, mColorWheel.getColor();, your app will crash because of a NullPointerException since the object you're calling a method on hasn't been instantiated.

If we had defined the getColor() method as static, we wouldn't need to make a new ColorWheel object, but we would be calling the method off the the name of the class, not a variable name (ColorWheel.getColor() instead of mColorWheel.getColor()).

I noticed the code you posted where you said it still worked shows the definition of a ColorWheel object, but then you're calling a method off of your FactBook object, this may have been a point of confusion for you.

You need to use the keyword new when you want to create an object. It means that the compiler need to create an object and keep it in memory, for example :

User user = new User();

But if you want to store a property of your object you don't need to use new (because the object was created before), for example:

String name = user.getName()

In the last example you are only declaring a reference to the user's name.