Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use "new" when creating a new instance of an object or variable?

 
J Steele
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have noticed that sometimes "new" is omitted when creating a new variable. Specifically, I have seen this when creating a new int or String. What are the rules regulating when you have to use "new" or just declare a variable? For example:
 
T Mishra
Ranch Hand
Posts: 108
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This should get you started with Java. Instantiating primitives and objects
 
J Steele
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the resources - exactly what I was looking for!
 
Stevens Miller
Bartender
Posts: 1223
23
C++ Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"new" is not relevant to the creation of a variable. It is used to create an instance of a class, also called an "object." It returns a reference to the newly created object, which may be stored in a variable of a type matching that of the object's class. In Line 1, you have created a variable that is of type int, which is a primitive, not a class. Anything that returns an integer may be stored in that variable. In Line 2, you have created a variable of type String. A reference to any String object may be stored in that variable. In Line 3, you have created a variable of type MyClass. A reference to any MyClass object may be stored in that variable. As it happens, in Line 3, you are also creating a new object of type MyClass. Well, you're not doing that, because you haven't completed the syntax necessary to invoke a constructor. Most likely, it would look like this:

There is no way, without knowing the class's constructor signature(s) to be sure, however, if the parenteses should be empty, or enclose an argument list. However, once a new object has been created, its reference (returned by new) can be stored in any variable of type MyClass.

Lines 3 could be rewritten thus:


Again, that's because variables are created independently of any objects, and new is used to create new objects.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic