Why do you have two class names when defining an object?

xiaoxiao2021-03-31  208

For example, we have declared a class named Balloon. Balloon objects can be generated in the formula (this is the usual language in Java or C books. The so-called Balloon object, said to understand the object, which is based on class balloon as template.):

Balloon rope1 = new balloon ();

For this statement, some people have asked almost all BBS: this class name Balloon, why do you have to appear twice? I have been wondering. Later, I saw it seems a bit of understanding, and I wrote it to let everyone criticize.

In fact, this statement is a three-step, which is to include three actions: create a Balloon object; create a balloon reference (so-called Balloon reference refers to the reference to the Balloon object.); Make the newly created Balloon reference point to the new The Balloon object created.

We break them to see. The first sentence:

Balloon rope1;

Just create a Balloon reference. It didn't point to anything. The second sentence:

NEW balloon ();

Created a Balloon object. However, it is not associated with any reference. It is like a balloon, but I don't have the rope to live it, it flies. This object cannot be used, which has become a waste in memory, will be recycled by Java garbage collection mechanism.

Therefore, the second and third steps of the three steps cannot be separated, only together:

Rope1 = new balloon ();

Now we have a statement

Balloon rope1 = new balloon ();

Why should I use two balloon problems, it should be figured out. The class name Balloon on the left is used to create a Balloon reference, and the class name Balloon on the right is used to create a Balloon object. There are no one in their respective divisions.

I named the class in the example Balloon (balloon), named the object reference to ROPE (rope), metaphor between the relationship between objects and references.

We didn't see the name of the object (many people used the reference Rope as an object), why? I thought the object was created in the heap space using dynamic allocation (also called a heap assignment). For any entity in the stack space, although they are actually existing, our code is invisible to them, can't touch. I can't name it, I didn't use it. Objects can only be accessed by reference.

You can have a idle reference (no rope of any balloon), you can't have a idle object (no rope is taking it). There is no object that references points to, it becomes garbage in memory, which will be reclaimed by the Garbage Collection mechanism of Java. Specifically, an object, at least one reference pointing to it, also allowing multiple references to point to it; a reference, can not point to the object, or point to one (only one) object.

These are not only in Java, and it is estimated that other object-oriented languages ​​are almost.

转载请注明原文地址:https://www.9cbs.com/read-130865.html

New Post(0)