Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Kelvin Warui
Courses Plus Student 878 Pointscreating 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
28,521 PointsIn 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
Courses Plus Student 878 PointsKelvin Warui
Courses Plus Student 878 PointsThanks 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
28,521 Pointsandren
28,521 PointsObjects 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 instantiatedContext
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.Kelvin Warui
Courses Plus Student 878 PointsKelvin Warui
Courses Plus Student 878 PointsI get it now thank you