Objects are instantiated (created) in different ways in various oo languages. In C #, when declaring a user-defined type variable, such:
Student y;
But declared the reference variable y of the studnet type. The referenced variable may point to a student object, but it is not yet; or its value is null, and null is the C # keyword to indicate that the object does not exist.
The special C # Operator -- New -- must be used to create a brand new student object in the memory and associate the new object with the referenced variable Y, as shown below:
Y = new student ();
Behind the scenes, we actually associate the physical memory address created by the object with the variable Y.
Think of the newly created object as a hydrogen balloon, and the referenced variable is the hand holding the balloon, so that the object can be accessed at any time.
Variables are sometimes seen as "caught" objects in informal ways, so we often use informal terms.Handle (handle)For example, "reference variable Y maintains the handle of a student object ".
You can also create a new object without specifying a reference variable immediately.Code:
New student ();
But such an object is like a hydrogen balloon without a rope: it may exist, but it cannotProgram. It will be out of memory.
Note: You can combine the declared referenced variables with the objects that actually point to the instantiated variables and use a line of code to represent them:
Student y = new studnet ();
Another way to initialize an application variable is to give it an existing object: it has been referenced for another different reference variable ("hand") ("grab ") object ("hydrogen balloon "). Let's look at an example.
// Declare the referenced variable and instantiate the first student object
Student x = new student ();
// Declare the Second referenced variable, but do not instantiate the second studnet object.
Student y;
// Pass a "handle" to Y, which belongs to all objects of Y
// (X continues to master it ). Now we have two ropes tied to the same balloon.
Y = X;