When is it necessary to use the new
keyword in Java. I know you are supposed to use it when you create an instance of an object like this:
TextView textView = new TextView(this);
Sometimes in code I notice that new
isn't used and I get confused..
In this line of code:
AssetManager assetManager = getAssets();
Why isn't an instance of the AssetManager created like this:
AssetManager assetManager = new AssetManager();
then it is set equal to getAssests()?
When should new
be used?
Thanks!
You use the new keyword when an object is being explicitly created for the first time. Then fetching an object using a getter method new is not required because the object already exists in memory, thus does not need to be recreated.
if you want a more detailed description of new visit the oracle docs
An object will need the 'new' keyword if it is null (which is fancy for not initialized).
EDIT:
This will always print "needs new" under the current circumstances.
Object mObj = null;
if (mObj == null)
System.out.println("needs new");
else
System.out.println("does NOT need new");
OUTPUTS: needs new
So to fix it, you would do something like:
Object mObj = new Object();
if (mObj == null)
System.out.println("needs new");
else
System.out.println("does NOT need new");
OUTPUTS: does NOT need new
And under those circumstances we will always see "does NOT need neW"
In java you always have to use new
to instantiate objects (well, almost always). With getAssests()
you retrieve an already created one. I guess your question comes from c++ where new
allocates dynamic memory, but since java has only dynamic objects, new is always needed.
In Java, new MyClass()
creates a new instance of MyClass
and returns a reference to it.
Meanwhile, the declaration:
MyClass foo;
defines a variable foo
that can store a reference to an instance of MyClass
, or the special value null
that indicates the absence of such a reference. If you don't assing any reference to foo
, its default value will be null
.
You can certainly combine these things, e.g. like this:
MyClass foo; // define a variable foo that can store an object reference
foo = new MyClass(); // create a new object and assign a reference to it to foo
or, equivalently, like this:
MyClass foo = new MyClass(); // combined variable definition and assignment
But you don't have to create a new instance every time you assign something to a reference variable. You could just as well do e.g. this:
MyClass foo, bar; // define two reference variables, foo and bar
foo = new MyClass(); // create a new object and assign a reference to it to foo
bar = foo; // now foo and bar point to the same object
or even:
MyClass foo = new MyClass(), bar = foo; // same, but shorter
Note that in Java, as opposed to some other languages like C++, you can never assign (a copy of) an actual object into a variable. Rather, Java objects are always accessed via references to them. When someone speaks of "assigning an object to a variable" or "passing an object as a parameter" or "returning an object from a method" in Java, what they always actually mean is assigning or passing or returning a reference to an object.
Methods that your code calls can (and often do) also return references to objects. For example, if your class had a method like this:
private MyClass getSomeObject() {
// ...some code here...
}
you could call it and save the reference it returns into a variable like this:
MyClass foo;
foo = getSomeObject();
or like this:
MyClass foo = getSomeObject();
We can tell from the method declaration that getSomeObject()
will always return a reference to a MyClass
instance (or null
), but not where that instance actually comes from. That depends entirely on what the code inside the getSomeObject()
method does. The code might always create a new MyClass
instance with new MyClass()
every time it's called, and return a reference to it, or it might always return a reference to the same object. Or, of course, it could sometimes return a reference to a new object, and sometimes to a previously created one.
Note that, if you assign a new value to a variable, whatever the variable contained before will be forgotten. If the forgotten value happens to be the last reference to some object, then that object itself will be destroyed by Java's garbage collector.
So, for example, while it's certainly possible to do something like this:
MyClass foo = new MyClass(); // create a new object and assign (a reference to) it to foo
foo = getSomeObject(); // forget the previous content of foo and replace it with whatever getSomeObject() returns
that normally makes no sense, since you'd be creating a new MyClass
instance just to immediately throw away your only reference to it and replace it with something else. In effect, the code above is exactly equivalent to:
new MyClass(); // create a new object and throw away(!) the reference to it
MyClass foo = getSomeObject(); // assign whatever getSomeObject() returns to foo
The only time that could even remotely make sense would be if you wanted to create a new MyClass
instance and immediately let it be garbage collected, e.g. because the MyClass
constructor had some side effect that you wanted to trigger. But since it's usually considered bad style for constructors to have any non-trivial side effects (or, more generally, to do anything besides setting up the new object), you shouldn't normally have any excuse for writing such code.
The new is used when you call the constructor for a function. getAssets() returns an AssetManager, it doesn't need to create a new one.
new
is always used to create new object.
this
AssetManager assetManager = getAssets();
is just assignation a value returned from method getAssets()
to reference assetManager
.
[edit]
i lied about new
it is possible to do something like this:
Foo.class.newInstance();
and also you can use reflection:
Foo.class.getDeclaredConstructors(Class[] parameterTypes).newInstance(arguments);
By using new
you allocate memory for the object.
Using a getXXX()
is used to get an existing object which is already allocated.
Since you flagged this with [android], I'm guessing your code is inside of an Activity
or Service
. In this case, getAssets()
is a method of the class you are extending. So you aren't actually creating it, you are asking the existing code to give you a reference to what already exists.
notice the capital letter in TextView, and the lack of it in getAssets. getAssets isn't a class like TextView, it's a method returning an object. And like many others mentioned, your asset already exists.
来源:https://stackoverflow.com/questions/8765351/when-is-the-appropriate-time-to-use-the-new-keyword