What Does the 'New' Keyword Actually Do in Java, and Should I Avoid Creating New Objects

What does the new keyword do here?

new my_class() creates a new object of type my_class. It is not assigned; so it is discarded.

But before being discarded, the object is built anyway; the constructor is run and prints its object's a attribute value. 8.

Benefits of Avoiding 'new' Keword When Creating Object in Java

What you read in the blog must have been about factory methods and similar techniques, which don't avoid new, but rather place it behind a more flexible API.

There are definetely no overarching downsides to the new operator. It has been, and will remain, the staple of any Java code, and the most natural way to actually create an object, as opposed to satisfying a more generic concern, such as "provide me with an entry point to your API".

All other techniques that create objects without involving new are special-purpose tools (cloning, deserialization, etc.).

Is the `new` keyword in java redundant?

Methods and constructors can have the same name.

public class NewTest {

public static void main(final String[] args) {
TheClass();
new TheClass();
}

static void TheClass() {
System.out.println("Method");
}

static class TheClass {
TheClass() {
System.out.println("Constructor");
}
}
}

Whether this language design choice was a good idea is debatable, but that's the way it works.

Role of new keyword in Java

new always creates a new instance (so always reserves heap memory, etc.).

This should illustrate it. note that == on an instance will tell you if it is the same instance (object) or a different one. (which is why you should always use equals, unless this is what you want to do)

I've added a funny thing happening with strings. "abc" does not create a new instance, but reuses an existing one. but when you call new on the String class it does.

public class Test {
private String value;

public String getValue() {
return value;
}

public Test() {
value = "default";
}
public Test(Test t) {
this.value = t.getValue();
}

public Test(String value) {
this.value = value;
}

public static void main(String[] argv) {
Test t1 = new Test();
Test t2 = new Test(t1);

if (t1 == t2) {
System.out.println("t1 == t2. should not happen");
} else {
System.out.println("t1 is a different instance from t2");
}

String s1 = "test";
String s2 = "test";

if (s1 == s2) {
System.out.println("s1 == s2. strings initialized with quotes don't always get a new instance.");
} else {
System.out.println("s1 is a different instance from s2. should not happen");
}

String s3 = new String("test");
String s4 = new String(s3);

if (s3 == s4) {
System.out.println("s3 == s4. should not happen.");
} else {
System.out.println("s3 is a different instance from s4, as they were newed.");
}

}
}

What is the 'new' keyword in JavaScript?

It does 5 things:

  1. It creates a new object. The type of this object is simply object.
  2. It sets this new object's internal, inaccessible, [[prototype]] (i.e. __proto__) property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).
  3. It makes the this variable point to the newly created object.
  4. It executes the constructor function, using the newly created object whenever this is mentioned.
  5. It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead.

Note: constructor function refers to the function after the new keyword, as in

new ConstructorFunction(arg1, arg2)

Once this is done, if an undefined property of the new object is requested, the script will check the object's [[prototype]] object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript.

The most difficult part about this is point number 2. Every object (including functions) has this internal property called [[prototype]]. It can only be set at object creation time, either with new, with Object.create, or based on the literal (functions default to Function.prototype, numbers to Number.prototype, etc.). It can only be read with Object.getPrototypeOf(someObject). There is no other way to get or set this value.

Functions, in addition to the hidden [[prototype]] property, also have a property called prototype, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.


Here is an example:

ObjMaker = function() { this.a = 'first'; };
// `ObjMaker` is just a function, there's nothing special about it
// that makes it a constructor.

ObjMaker.prototype.b = 'second';
// like all functions, ObjMaker has an accessible `prototype` property that
// we can alter. I just added a property called 'b' to it. Like
// all objects, ObjMaker also has an inaccessible `[[prototype]]` property
// that we can't do anything with

obj1 = new ObjMaker();
// 3 things just happened.
// A new, empty object was created called `obj1`. At first `obj1`
// was just `{}`. The `[[prototype]]` property of `obj1` was then set to the current
// object value of the `ObjMaker.prototype` (if `ObjMaker.prototype` is later
// assigned a new object value, `obj1`'s `[[prototype]]` will not change, but you
// can alter the properties of `ObjMaker.prototype` to add to both the
// `prototype` and `[[prototype]]`). The `ObjMaker` function was executed, with
// `obj1` in place of `this`... so `obj1.a` was set to 'first'.

obj1.a;
// returns 'first'
obj1.b;
// `obj1` doesn't have a property called 'b', so JavaScript checks
// its `[[prototype]]`. Its `[[prototype]]` is the same as `ObjMaker.prototype`
// `ObjMaker.prototype` has a property called 'b' with value 'second'
// returns 'second'

It's like class inheritance because now, any objects you make using new ObjMaker() will also appear to have inherited the 'b' property.

If you want something like a subclass, then you do this:

SubObjMaker = function () {};
SubObjMaker.prototype = new ObjMaker(); // note: this pattern is deprecated!
// Because we used 'new', the [[prototype]] property of SubObjMaker.prototype
// is now set to the object value of ObjMaker.prototype.
// The modern way to do this is with Object.create(), which was added in ECMAScript 5:
// SubObjMaker.prototype = Object.create(ObjMaker.prototype);

SubObjMaker.prototype.c = 'third';
obj2 = new SubObjMaker();
// [[prototype]] property of obj2 is now set to SubObjMaker.prototype
// Remember that the [[prototype]] property of SubObjMaker.prototype
// is ObjMaker.prototype. So now obj2 has a prototype chain!
// obj2 ---> SubObjMaker.prototype ---> ObjMaker.prototype

obj2.c;
// returns 'third', from SubObjMaker.prototype

obj2.b;
// returns 'second', from ObjMaker.prototype

obj2.a;
// returns 'first', from SubObjMaker.prototype, because SubObjMaker.prototype
// was created with the ObjMaker function, which assigned a for us

I read a ton of rubbish on this subject before finally finding this page, where this is explained very well with nice diagrams.

When is the appropriate time to use the 'new' keyword?

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"

Is new expensive in java?

Memory allocation is vastly different between these languages; this a big subject and it cannot be reduced to a simplistic question like whether new in java works "in a similar fashion" as in C++.

To give you a simplistic answer, it certainly does not work in a similar fashion because in Java you never need to delete.

To make you happier, let me also add that new in Java is purported to be a lot faster than in C++, because the runtime does not need to maintain linked lists of allocated and free blocks, and it does not have to search for a gap that is large enough to contain the block you need. Also, it does not suffer from the memory fragmentation problems that you may encounter with C++.

Most of the time, (if you are running under plentiful memory conditions, and in modern days we usually are,) the java runtime simply has a pointer pointing at the boundary between the allocated memory and the free memory, it takes a copy of that pointer, it adds the number of bytes that you want to the pointer, and it returns the copy to you. The overhead comes later, during garbage collection.

So, overall, java tends to give you memory quicker than C++ does, but it adds a certain overhead dispersed over your entire runtime due to frequent and complicated garbage collection. This overhead is unavoidable, and somewhat unpredictable, but on modern machines it is mostly (though not always) imperceptible.

The bottom line is that from the start, Java aimed to free programmers from having to worry about memory allocation, and to a very large extent it has been very successful in doing so. It is only under extremely rare, highly exceptional circumstances, that java programmers need to worry about pre-allocating objects, implementing their own object pools, etc. All these things are mostly non-issues in java.



Related Topics



Leave a reply



Submit