JAVA object reference, object assignment, and java assignment

Source: Internet
Author: User

JAVA object reference, object assignment (conversion), and java assignment

Link: http://zwmf.iteye.com/blog/1738574

 

Keywords: java object reference

Java object and its reference

Some basic concepts about objects and references.

When I was a beginner in Java, I thought the basic concepts were vague for a long time. Later, I learned that in many Java books, objects and object references are confused. However, if I cannot tell between objects and object references,




It is really hard to understand the following object-oriented technology. Writing down your own understanding may reduce Java beginners from detours.

To facilitate the description, we first define a simple class:

Class Vehicle {

Int passengers;

Int fuelcap;

Int mpg;

}

With this template, you can use it to create objects:

Vehicle veh1 = new Vehicle ();

Generally, the action of this statement is called to create an object. In fact, it contains four actions.

1) the "new Vehicle" on the right is a Vehicle class template that creates a Vehicle class Object (also referred to as a Vehicle object) in the heap space ).

2) The () at the end means that after the object is created, the Vehicle class constructor is called immediately to initialize the newly generated object. Constructors are certainly there. If you do not write it, Java will add you a default constructor.

3) "Vehicle veh 1" on the left creates a Vehicle class reference variable. The so-called Vehicle class reference is an object reference that can be used to point to the Vehicle object in the future.

4) The "=" operator directs the object reference to the created Vehicle object.

We can split this statement into two parts:

Vehicle veh1;

Veh1 = new Vehicle ();

The results are the same. In this way, it is clear that there are two entities: one is the object reference variable, and the other is the object itself.

The object created in the heap space is different from the object created in the Data Segment and stack space. Even though they are actually entities, they are invisible and invisible. Not only that,

Let's take a closer look at the second sentence and find out the name of the newly created object? It is said to be "Vehicle ". No. "Vehicle" is the name of the class (Object creation template.

A Vehicle class can create countless objects accordingly. These objects cannot all be called "Vehicle ".

The object does not even have a name and cannot be accessed directly. We can only indirectly access objects through object reference.

To visually describe objects, references, and relationships between them, we can make a metaphor that may be inappropriate. The object is like a very large balloon, so big that we can't catch it. The referenced variable is a rope that can be used to fasten the balloon.

If only the first statement is executed and the second statement is not executed, the referenced variable veh1 has not pointed to any object yet, and its value is null. The referenced variable can point to an object or be null.

It is a rope that has not been tied to any balloon. After the second sentence is executed, a new balloon is made and tied to the veh1 rope. We caught the rope, and we caught the balloon.

Another sentence:

Vehicle veh2;

I made another rope and didn't fasten the balloon. If you add:

Veh2 = veh1;

Fasten it. Here, a replication occurs. However, it should be noted that the object itself is not copied, And the Copied object is only referenced. The result is that veh2 also points to the object pointed to by veh1. The two ropes are tied to the same balloon.

If you use the following sentence to create another object:

Veh2 = new Vehicle ();

The reference variable veh2 points to the second object.

From the above descriptions, we can draw the following conclusions:

(1) An object reference can point to 0 or 1 objects (a rope can be without a balloon or a balloon );

(2) An object can have N references pointing to it (N Ropes can hold a balloon ).

If the following statement is used:

Veh1 = veh2;

According to the above inference, veh1 also points to the second object. This is okay. What is the first object? No rope tied it, and it flew. In most books, it is recycled by Java's garbage collection mechanism.

This is not exact. Correctly, it has become the processing object of the garbage collection mechanism. When the garbage collection mechanism is actually being recycled depends on the mood of the garbage collection mechanism.

In this case, should the following statements be invalid? At least it's useless, right?

New Vehicle ();

No. It is legal and available. For example, if we only generate an object for printing, we do not need to use reference variables to hold it. The most common one is to print strings:

System. out. println ("I am Java !");

String object "I am Java !" It is discarded after printing. Someone calls this object a temporary object.

The relationship between the object and the reference continues until the object is recycled.



Java objects and references



Java objects and references are confusing but basic knowledge that must be mastered. This chapter describes the concepts of Java objects and references, as well as the parameters that are closely related to them.



First look at the following program:

StringBuffer s;

S = new StringBuffer ("Hello World! ");

The first statement only allocates space for reference, and the second statement allocates space for reference by calling the StringBuffer constringbuffer (String str) constringbuffer) generates an instance (or an object) for the class ). After these two operations are completed, the object content can be accessed through s-in Java, the object is manipulated through reference.



The relationship between Java objects and references can be said to be interrelated, but independent of each other. Mutual independence is mainly manifested in: reference can be changed, it can point to another object, such as the above s, you can give it another object, such:

S = new StringBuffer ("Java ");

In this way, s is separated from the first object it points.



In terms of storage space, objects and references are also independent. They are stored in different places, objects are generally stored in the heap, and references are stored in a faster stack.



References can point to different objects, and objects can be manipulated by multiple references, for example:

StringBuffer s1 = s;

This statement points s1 and s to the same object. Since two references direct to the same object, no matter which reference is used to manipulate the object, the content of the object changes, and there is only one copy. The content obtained through s1 and s is naturally the same, (except for String, because String remains unchanged, String s1 = "AAAA"; String s = s1, Operation s, and s1 remain unchanged, so another space is opened for s to store s,) the following procedure:

1 StringBuffer s; 2 3 s = new StringBuffer ("Java"); 4 5 StringBuffer s1 = s; 6 7 s1.append ("World"); 8 9 System. out. println ("s1 =" + s1.toString (); // The print result is: s1 = Java World 10 11 System. out. println ("s =" + s. toString (); // The printed result is: s = Java World 12 13

The above program shows that the content printed by s1 and s is the same, and this result looks confusing, but think about it carefully. s1 and s are just two references, and they are just joystick, they direct to the same object. They manipulate the same object and get the content of the same object. This is like the brakes and throttling of a car. They manipulate the speed of a car. If the speed of a car starts to 80, you step on the throttling and the car is accelerated. If the speed of a car is increased to 120, then you step on the brakes, and the speed starts to decrease from 120. If you drop to 60 and then step on the accelerator, the speed starts to rise from 60, instead of starting from 120 after the first step on the accelerator. That is to say, the speed is affected by both the throttling and the brakes, but they are accumulated rather than independent (unless the brakes and the throttling are not in a car ). Therefore, in the above program, no matter s1 or s is used to manipulate objects, their impact on objects also accumulates (more references are the same ).



Parameter passing can be understood only when the relationship between objects and references is understood.

Generally, questions about passing parameters in Java are taken into consideration in the interview questions. The standard answer is that Java only has one parameter passing method: passing by value, that is, passing everything in Java is passing values. If the input method is of the basic type, you will get a copy of the basic type. If a reference is passed, a copy of the reference is obtained.



In general, we can easily understand the transmission of basic types. For objects, we always feel like passing by reference. Let's look at the following program:

1 public class ObjectRef {2 3 4 5 // pass 6 7 public static void testBasicType (int m) {8 9 System. out. println ("m =" + m); // m = 5010 11 m = 100; 12 13 System. out. println ("m =" + m); // m = 10014 15} 16 17 18 19 // The parameter is the object and does not change the referenced value ?????? 20 21 public static void add (StringBuffer s) {22 23 s. append ("_ add"); 24 25} 26 27 28 29 // The parameter is an object and the referenced value is changed ????? 30 31 public static void changeRef (StringBuffer s) {32 33 s = new StringBuffer ("Java"); 34 35} 36 37 38 39 public static void main (String [] args) {40 41 int I = 50; 42 43 testBasicType (I); 44 45 System. out. println (I); // I = 5046 47 StringBuffer sMain = new StringBuffer ("init"); 48 49 System. out. println ("sMain =" + sMain. toString (); // sMain = init50 51 add (sMain); 52 53 System. out. println ("sMain =" + sMain. toString (); // sMain = init_add54 55 changeRef (sMain); 56 57 System. out. println ("sMain =" + sMain. toString (); // sMain = init_add58 59} 60 61}

The above results show that the testBasicType method parameter is the basic type, although the m value is changed, but does not affect I.

The parameter of the add method is an object. When sMain is passed to parameter s, s obtains the copy of sMain, so s and sMain point to the same object. Therefore, the s operation actually affects the object pointed to by sMain. Therefore, after the add method is called, the content of the object pointed to by sMain changes.

In the changeRef method, parameters are also objects. When sMain is passed to parameter s, s gets the copy of sMain, but unlike the add method, in the method body, the object s points to (that is, s points to another object, and the rope holding the balloon changes to the balloon). After the value is assigned to s, s and sMain are no longer associated, sMain and sMain point to different objects. Therefore, no matter what operations are performed on s, the object to which sMain points will not be affected. Therefore, the content of the object that sMain points to before and after the changeRef method is called has not changed.



Many people may feel this way about the calling result of the add method: Isn't it passed by reference clearly? To solve this problem, use Bruce Eckel: It depends on how you think about references. In the end, you will understand that this argument is not that important. What really matters is that you need to understand that transferring a reference makes the modification of the (caller's) object unpredictable.

1 public class Test 2 {public int I, j; 3 public void test_m (Test a) 4 {Test B = new Test (); 5 B. I = 1; 6 B. j = 2; 7 a = B; 8} 9 public void test_m1 (Test a) 10 {. I = 1; 11. j = 2; 12} 13 public static void main (String argv []) 14 {Test t = new Test (); 15 t. I = 5; 16 t. j = 6; 17 System. out. println ("t. I = "+ t. I + "t. j = "+ t. j); // 5,618 t. test_m (t); 19 System. out. println ("t. I = "+ t. I + "t. j = "+ t . J); //, a and t both point to an object, and in test_m s points to another object, so the object t remains unchanged !!! 20 21 t. test_m1 (t); 22 23 System. out. println ("t. I = "+ t. I + "t. j = "+ t. j); // 1,224 25} 26 27}

There is only one answer: in Java, parameters are passed by value. In fact, we need to understand what happens when the parameter is an object and the reference is passed (just like the add method above )?



========================================================== ======================================

Let's record this question.
The following expression:
A a1 = new ();
It indicates that A is A class, a1 is A reference, a1 is not an object, new A () is an object, and a1 references the object new.

In JAVA, "=" cannot be considered as a value assignment statement. It is not assigning an object to another object, in essence, the execution process transmits the address of the right object to the reference on the left, so that the reference on the left points to the object on the right. JAVA does not seem to have a pointer on the surface, but its reference is actually a pointer. The reference is not an object, but the address of the object, so that the reference points to the object. In JAVA, the "=" statement should not be translated into a value assignment statement, because it is indeed not a value assignment process, but an address transfer process, being translated into a value assignment statement may cause many misunderstandings and inaccurate translations.



Another example is:
A a2;
It indicates that A is A class, a2 is A reference, a2 is not an object, and a2 points to an empty null object;



Another example is:
A2 = a1;
It indicates that a2 is a reference, a1 is a reference, and the address of the object pointed to by a1 is passed to a2, so that a2 and a1 point to the same object.

In summary, we can simply record it as an object on the left of the "=" statement during initialization, while the object is new on the right.
When both the left and right references the = Statement, both the left and right references the object pointed to by the right reference.

Another example is actually a synonym for objects.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.