Google Website Translator Gadget

domingo, 5 de febrero de 2012

Java: Declaring an object


Java logo
docs.oracle.com
From:
http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html





Declaring a Variable to Refer to an Object
Previously, you learned that to declare a variable, you write:
type name;

This notifies the compiler that you will use name to refer to data whose type is type.
With a primitive variable, this declaration also reserves the proper amount of memory for the variable.

However:
Point originOne;

If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it.
Simply declaring a reference variable does not create an object.
For that, you need to use the new operator, as described in the next section.
You must assign an object to originOne before you use it in your code. Otherwise, you will get a compiler error.

A variable in this state, which currently references no object, can be illustrated as follows (the variable name, originOne, plus a reference pointing to nothing):




Instantiating a Class
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.


--------------------------------------------------------------------------------
Note : The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
--------------------------------------------------------------------------------

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:

Point originOne = new Point(23, 94);

No hay comentarios:

Publicar un comentario