简体   繁体   中英

Instantiating an object

In java, i have learned that i use the new keyword to instantiate an object eg

 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();

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM