JAVA object reference, and object assignment

Source: Internet
Author: User
Tags null null

Keyword: Java object reference

Java objects and their references

Some basic concepts between objects and references.

Beginner Java, for a long time, always feel that the basic concept is very vague. Later, in many Java books, the references to objects and objects are confused. However, if I can't tell the object from the object reference,

That's really not a good way to understand the following object-oriented techniques. Write down a little bit of yourself, maybe let the beginner Java friends to take a little detour.

For illustrative purposes, we will 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 ();

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

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

2) The end of the () means that immediately after the object is created, the constructor of the vehicle 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) "Vehicle Veh 1" On the left creates a Vehicle class reference variable. The so-called vehicle class reference is the object reference that can then be used to point to the vehicle object.

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:

Vehicle VEH1;

VEH1 = new Vehicle ();

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 say it is called "Vehicle". No, "Vehicle" is the name of the class (the object's creation template).

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

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 VEH1 created does not yet point to any object whose 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 rope on the VEH1. We grabbed the ball by grasping the rope.

One more sentence:

Vehicle Veh2;

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

VEH2 = VEH1;

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, VEH2 also points to the object that VEH1 points to. Two ropes are the same balloon.

If you create an object with the following sentence:

VEH2 = new Vehicle ();

The reference variable, VEH2, 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:

VEH1 = VEH2;

According to the above inference, VEH1 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 Vehicle ();

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

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 class ObjectRef {

Parameter passing of a primitive type

public static void Testbasictype (int m) {

System.out.println ("m=" + m);//m=50

m = 100;

System.out.println ("m=" + m);//m=100

}

parameter is an object, does not change the value of the reference??????

public static void Add (StringBuffer s) {

S.append ("_add");

}

parameter is the object, change the value of the reference?????

public static void Changeref (StringBuffer s) {

s = new StringBuffer ("Java");

}

public static void Main (string[] args) {

int i = 50;

Testbasictype (i);

System.out.println (i);//i=50

StringBuffer Smain = new StringBuffer ("Init");

System.out.println ("smain=" + smain.tostring ());//smain=init

Add (Smain);

System.out.println ("smain=" + smain.tostring ());//smain=init_add

Changeref (Smain);

System.out.println ("smain=" + smain.tostring ());//smain=init_add

}

}

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.

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.

public class Test
{public int i,j;
public void Test_m (test a)
{Test b = new Test ();
B.I = 1;
B.J = 2;
A = b;
}
public void test_m1 (test a)
{A.I = 1;
A.J = 2;
}
public static void Main (String argv[])
{Test t= new test ();
T.I = 5;
T.J = 6;
System.out.println ("t.i =" + t.i + "t.j=" + T.J); 5,6
T.test_m (t);
System.out.println ("t.i =" + t.i + "t.j=" + T.J); 5,6,a and T both point to an object, and in test_m s it points to another object, so the object T is the same!!!

T.TEST_M1 (t);

System.out.println ("t.i =" + t.i + "t.j=" + T.J); The

}

}

There is only one answer: Java is a parameter that is 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.

If you need to assign a value, you need the class to implement the Cloneable interface to implement the Clone () method.

1234567891011
Class D implements cloneable{//implements Cloneable interface string sex;d (String sex) {this.sex=sex;} @Overrideprotected Object Clone () throws Clonenotsupportedexception {//Implement Clone method return Super.clone ();}}

When assigning a value:

12
D d=new D ("male");D d2= (d) d.clone ();//Assign D to D2

If a variable in a class is not a primary type, but an object, you also need to call the object's clone () method
The following is a complete example:

1234567891011121314151617181920212223242526272829303132333435363738394041
public class Test2 {public static void main (string[] args) throws Clonenotsupportedexception {//TODO auto-generated Metho D stubd d=new D ("male"); C c=new C ("Zhang San", "a", d); C new_c= (c) c.clone ();//Call the Clone method to assign a value new_c.name= "John Doe";d. sex= "female";//dsystem.out.println (C.d.sex); System.out.println (C.name); }} class C implements cloneable{string name; String age;d D; C (String name,string age,d D) throws clonenotsupportedexception{this.name=name;this.age=age;this.d= (d) d.clone ();// Call the Clone method to assign a value so that if the external D changes, the C will not change} @Overrideprotected Object Clone () throws Clonenotsupportedexception {//TODO Auto-generated method Stubreturn Super.clone ();}} Class D implements cloneable{//implements Cloneable interface string sex;d (String sex) {this.sex=sex;} @Overrideprotected Object Clone () throws Clonenotsupportedexception {//Implement Clone method return Super.clone ();}}

Original: http://blog.sina.com.cn/s/blog_4cd5d2bb0100ve9r.html

clone:http://bxkqzjt521.blog.163.com/blog/static/202818420119102362458/

JAVA object reference, and object assignment

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.