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

Kelvin Warui
PLUS
Kelvin Warui
Courses Plus Student 878 Points

creating java instances with the new keyword vs instances that you get using get methods

i am puzzled as to why we don't use the new keyword everytime we need an instance of a particular class.For example when creating the context object we do this:

Context context = getApplicationContext();

Why not create an instance of context using the new keyword like this

Context context = new Context();

would someone please elaborate ?

1 Answer

andren
andren
28,558 Points

In your first example you are not creating a new instance of Context, you are retrieving an existing Context (the Context that belongs to the application) which was created at some earlier time. In your second example you are creating a new Context completely from scratch which is not the same thing.

Kelvin Warui
Kelvin Warui
Courses Plus Student 878 Points

Thanks for the feedback,i thought in java if you always wanted to use an object of a certain class you had to create it from scratch inorder to invoke its functions ?

andren
andren
28,558 Points

Objects do have to be instantiated at some point, that is correct. But you can pass an instantiated object around just like you can any other value.

The getApplicationContext method returns an instantiated Context object that was created earlier in some other class. So it is instantiated from scratch at some point, just not by code you personally wrote.