Original:
http://zwmf.iteye.com/blog/1738574
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:
Java code
- stringbuffer s;
-
- s = < span class= "keyword" >new stringbuffer (
-
- stringbuffer s1 = s;
-
- S1.append ( Span class= "string", " world");
-
- System.out.println ( "s1=" + s1.tostring ()); //print result: s1=java world
-
- System.out.println (
-
-
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:
Java code
- Public class ObjectRef {
- //Basic type of parameter passing
- 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 for 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 the object, when the Smain passed to the parameter S, S gets the copy of the Smain, but unlike the Add method, in the method body changed the object of S (that is, s pointing to other objects, holding the balloon of the rope to change the balloon), to S re-assigned value, S has nothing to do with Smain, it and Smain point to different objects, so no matter what action on S does not affect the Smain point to the object, it is called Changeref method before and after the object content of Smain point 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.
Java code
- 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); //1,2
- }
- }
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.
Forwarding: Java objects and their references