"Reprint" JAVA object reference, and object assignment

Source: Internet
Author: User
Tags null null

Let's first clarify the difference between the object and the reference, for illustrative purposes, we define a simple class:

 Public class Person {    int age ;}

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

Person person=person ();

Usually the action of this statement is called the creation of an object, in fact, it contains four of actions.

1) The "new person" on the right is a template for the person class, creating a Person class object (also referred to as the person object) in the heap space.

2) The end of the () means that immediately after the object is created, the constructor of the person class is called, initializing the object that was just generated. Constructors are definitely there. If you do not write, Java will give you a default constructor.

3) The person person on the left creates a reference variable for the person class. The so-called person class reference is the object reference that can be used to point to the person object later.

4) The "=" operator causes the object reference to point to the vehicle object that was just created.

We can split this statement into two parts:

Person Person;person New Person ();

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

The entities created in the heap space are different from the entities created in the data segment and in the stack space. Even though they are entities that do exist, we cannot see or touch them. Not only this,

Let's take a closer look at the second sentence and find out what the name of the object you just created. Some people say that it is called "person". No, "person" is the name of the class (the object's creation template).

A person class can create countless objects on this basis, and these objects cannot be called "man" at all.

The object has no name and cannot be accessed directly. We can only access objects indirectly through object references.

In order to visualize the object, the reference and the relationship between them, you can make a metaphor that may not be appropriate. The object is like a big balloon, so big that we can't hold it. A reference variable is a rope that can be used to tie a balloon.

If only the first statement is executed and no second is executed, the reference variable created by the person does not yet point to any object, and its value is null. A reference variable can point to an object, or null.

It is a rope, a rope that has not been tied to any of the balloons. After executing the second sentence, a new balloon was made and tied to the person's rope. We grabbed the ball by grasping the rope.

One more sentence:

Person Person2;

He made a rope again, not the SAIC ball. If you add one more sentence:

Person2= Person1;

It's tied up. Here, the replication behavior occurs. However, to illustrate, the object itself is not copied, only the object reference is copied. As a result, Person2 also points to the object that Person1 points to. Two ropes are the same balloon.

If you create an object with the following sentence:

person2= new Person ();

The reference variable, Person2, changes to a second object.

from the above narrative, we can obtain the following conclusions:

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

(2) An object can have n references pointing to it (there can be n ropes to tie a balloon).

If you come back to the following statement:

Person1= Person2;

According to the above inference, Person1 also points to the second object. That's fine. The question is, what about the first object? There was not a rope to tie it, it flew. Most books say it was recycled by Java's garbage collection mechanism.

It's not exactly. Correctly, it has become the object of garbage collection mechanism processing. As for when to really be recycled, it depends on the garbage collection mechanism mood.

In this view, the following statement should be illegal, right? At least it's useless, right?

New Person ();

Wrong. It is legal and available. For example, if we generate an object just for printing, we don't need to tie it with reference variables. The most common is to print a string:

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

String Object "I am java!" is discarded after printing. Some people call this object a temporary object.

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

Java objects and references are easy to confuse but must master, and this chapter describes the concepts of Java objects and references, and the parameters that are closely related to their delivery.

First look at the following program:

StringBuffer s;

s = new StringBuffer ("Hello world!");

The first statement allocates space only for references (reference), while the second statement generates an instance (or object) for the class by calling the constructor of the class (StringBuffer) StringBuffer (String str). When these two operations are completed, the object's contents can be accessed through S-- in Java, by reference to manipulate the object .

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

s = new StringBuffer ("Java");

As a result, s is detached from the first object it points to.

From a storage space, objects and references are also independent, stored in different places, objects are generally stored in the heap, and references are stored in faster stacks.

References can point to different objects, and objects can also be manipulated by multiple references, such as:

StringBuffer S1 = s;

This statement causes S1 and S to point to the same object. Since two references point to the same object, regardless of which reference is used to manipulate the object, the contents of the object change, and only one copy of the content obtained through S1 and S is naturally the same, except for string, because string is always the same, string s1= "AAAA"; String S=s1, Operation S,s1 because it is always the same, so it opens up space for S to store s, as in the following program:

StringBuffer s;

s = new StringBuffer ("Java");

StringBuffer S1 = s;

S1.append ("World");

System.out.println ("s1=" + s1.tostring ());//Print Result: S1=java World

System.out.println ("s=" + s.tostring ());//Print Result: S=java World

The above program shows that S1 and s print out the same content, the result seems to be very confusing, but think about, S1 and S is only two references, they are only the joystick, they point to the same object, manipulating the same object, through which they get the same object content. This is like the car brakes and throttle, they manipulate the speed, if the car starts at 80, then you step on the accelerator, the car accelerated, if the speed rose to 120, then you step on the brakes, at this time the speed is starting from 120, if the drop to 60, and then step on the throttle, The speed of the car starts from 60, not the first 120 after the throttle. That means the speed is affected by both throttle and brake, and their effects are cumulative, not independent (unless the brakes and throttle are not on a car). Therefore, in the above program, whether using S1 or s manipulation objects, their impact on the object is also cumulative (more references the same).

You can understand parameter passing only if you understand the relationship between the object and the reference.

General interview questions in the test of Java, and its standard answer is that Java has only one way to pass the parameter: that is, by value, that is, passing everything in Java is a pass value. If the incoming method is a basic type of thing, you get a copy of this basic type. If you are passing a reference, you get a copy of the reference.

In general, for the basic type of delivery, we are easy to understand, and for the object, always feel is to pass by reference, see the following program:

 Public classObjectRef { Public Static voidMain (string[] args) {inti = 50;        Testbasictype (i); System.out.println (i);//i=50StringBuffer Smain=NewStringBuffer ("Init"); System.out.println ("Smain=" + smain.tostring ());//Smain=initAdd (Smain); System.out.println ("Smain=" + smain.tostring ());//Smain=init_addChangeref (Smain); System.out.println ("Smain=" + smain.tostring ());//Smain=init_add    }    //parameter passing of a primitive type     Public Static voidTestbasictype (intm) {System.out.println ("m=" + M);//m=50m= 100; System.out.println ("m=" + M);//m=100    }    //parameter is an object, does not change the value of the reference??????      Public Static voidAdd (StringBuffer s) {s.append ("_add"); }    //parameter is the object, change the value of the reference?????      Public Static voidChangeref (StringBuffer s) {s=NewStringBuffer ("Java"); }}

The allowed results of the above program show that the parameters of the Testbasictype method are basic types, although the value of the parameter m changes, but does not affect I.

The argument to the Add method is an object, and when the Smain is passed to the parameter S, S gets a copy of the Smain, so s and Smain point to the same object, so the use of the S operation is actually the object that the Smain points to, so after calling the Add method, The content of the object pointed to by Smain has changed.

In the Changeref method, the parameter is also an object, and when the Smain is passed to the parameter S, S gets a copy of the Smain, but unlike the Add method, the object that s points to is changed in the method body ( that is, S pointing to another object , holding the balloon's rope for the balloon ), and giving s re-assigned value,s and Smain has no connection , it and Smain point to different objects, so whatever you do to s does not affect the object that the Smain points to, Therefore, the object content that the Smain points to before and after calling the Changeref method has not changed.

The key is to understand the "=", do not think it is an assignment operation, p=new person (); Indicates that P points to a person object;

P1=P2 indicates that P1 points to P2 objects, but how P1 changes does not matter to P2 itself, unless the P1 changes affect the object they are pointing to.

For the result of the call to the Add method, many people may have this feeling: Is it not obvious that it is passed by reference? For this kind of question, or to apply Bruce Eckel: It depends on how you look at the citation, and eventually you will understand that the argument is not so important. What really matters is that you understand that passing references makes changes to (the caller's) objects unpredictable.

 Packagemain; Public classHello { Public intI, J;  Public Static voidMain (String argv[]) {Hello Hello=NewHello (); HELLO.I= 5; HELLO.J= 6; System.out.println ("HELLO.I =" + hello.i + "hello.j=" + hello.j);//5,6hello.test1 (hello); System.out.println ("T.I =" + hello.i + "t.j=" + hello.j);//5,6,a and T both point to an object, and in Test_m a points to another object, so the object T is the same!!! hello.test2 (hello); System.out.println ("HELLO.I =" + hello.i + "hello.j=" + hello.j);// the    }    //A reference is passed, and the representation participates in the argument two references all point to the same object.      Public voidtest1 (Hello a) {Hello B=NewHello (); B.I= 1; B.J= 2; A=b; }     Public voidtest2 (Hello a) {A.I= 1; A.J= 2; }}

There is only one truth: in Java, parameters are passed by value. In fact, we need to understand what happens when a parameter is an object (like the Add method above).

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

Landlord, so to remember this question
The following expression:
A a1 = new A ();
It represents a is a class, A1 is a reference, A1 is not an object, new A () is the object, and the A1 reference points to the object of new A ().

In Java, "=" cannot be considered an assignment statement, it does not assign an object to another object, its execution essentially passes the address of the right object to the left reference, so that the left reference points to the object on the right. There is no pointer on the Java surface, but its reference is essentially a pointer, and the reference is not the object, but the address of the object, so that the reference points to the object. In Java, the "=" statement should not be translated into an assignment statement because it does not perform a process of assignment, but rather a process of passing an address, and being translated into an assignment statement can cause many misunderstandings and inaccurate translations.

Again such as:
A A2;
It represents a is a class, A2 is a reference, A2 is not an object, and the object pointed to by A2 is null null;

Again such as:
a2 = A1;
It stands for, A2 is a reference, A1 is also a reference, and the address of the object pointed to by A1 is passed to A2, which makes A2 and A1 point to the same object.

In summary, it can be simply remembered that, at initialization, the "=" statement to the left of the reference, the right new out of the object.
When the "=" statement is referenced around the back, the reference to the left and right refers to the object to which the reference is pointing.

Again the so-called instance, is actually the synonym of the object.

done!

"Reprint" JAVA object reference, and object assignment

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.