Reputation: 39
In java, i have learned that i use the new keyword to instantiate an object e.g
Employee e = new Employee();
In android ,by going through the developers page a context object is instantiated without using the new keyword like this :
Context myContext = getApplicationContext();
Why is this ? i should have thought that a context object should be created the same way using new keyword like this:
Context myContext = new Context();
I think someone might answer back saying that the getApplicationContext() method returns an object of type context and hence the syntax above,but does someone have a more deeper explanation as to why do this instead of simply doing this
Context myContext = new Context();
Upvotes: 2
Views: 391
Reputation: 14938
Because sometimes you simply don't want/need to create a new instance each time, sometimes you just want to get the object without actually handling its creation by yourself.
For example, there is a Singleton design pattern that in its common implementation makes it impossible to create a new instance with a new
keyword since a constructor is private. So what is left to do is get an instance of a class by calling a static method:
public class MySingleton {
private MySingleton() { }
public static MySingleton getInstance() { ... }
}
Sometimes you may want to use a Factory method pattern, that handles new object creation/instantiation as well: you call a single method and a new or existing object is returned for you without explicitly calling a constructor.
In case of Context, you don't need to create this object, because the system handles it for you and the process is transparent. You just need to call a single method and you have your instance.
Upvotes: 2
Reputation: 959
As stated in the docs:
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
So by using getApplicationContext()
, you are calling the context object which is containing your application-specific resources.
Creating a new Context
type object wouldn't make a sense since it's not containing information about your application environment.
Upvotes: 2
Reputation: 10019
From the docs:
Return the context of the single, global Application object of the current process.
So, when you launch the application, the system assigns a process to it. Doing Context c = new Context()
will not get you the instance of that process.
Upvotes: 2