What is an alias?
Use a simple example
Public class aliases {
INT I;
Public aliases () {i = 1;
Public aliases (INT I) {this.i = i;
Public static void main (string args []) {
Aliases a = new aliases ();
Aliases b = a; // a and b point to the same object, A and B alias
System.out.println ("A.i and B.I: A.I " " B.I);
System.out.println ("Add B:");
B.I ;
System.out.println (("A.i and B.I:" a.i "" b.i);}}
Output: A.i and B.I: 1 1
Add B:
A.i and B.I: 2 2
Obviously, A and B points to the same object, B = a This operation is just copied to b, and the object is not copied. Java is operated with REERCE, and it is an example of an explicit alias. When you pass an object to the function, you will have an alias, as follows:
Public class aliases {
INT I;
Public aliases () {i = 1;
Public aliases (INT I) {this.i = i;
Public Increment (aliases as) {as.i ;}
Public static void main (string args []) {
Aliases a = new aliases ();
System.out.println ("A.I Before Increment: A.i);
Increment (a);
System.out.println ("A.I After Increment: a.i);
}
}
You can see that a change in the value of I after the call of the function increment (). In some cases, you may not want the incoming object to change, you want the object within the function to be induced into the object, the change of this copy does not affect the original object, how to deal with it? We know that C is by declaring consts, which means that this parameter cannot be changed, but don't forget, C has a so-called copy constructor, so the object in the function is indeed a copy, and Java does not support copy constructor The reason is obvious, Java passes the reference to the object, you just count the copy there is also a copy of the reference (so some people say that Java is essentially transmitted). So there is no way? Yes, that is, "clone mechanism", in root Object has defined Clone () methods, you have to do just the Cloneable interface, and override the clone () method, typical apps
Class Cloneclass Implements Cloneable {
Public int.
Public Object Clone () {
Cloneclass o = null;
Try {
o = (cloneClass) super.clone ();
} catch (clonenotsupportedexception e) {
E.PrintStackTrace ();
} Return O;
}
Call the super.clone () method, which automatically processes the storage allocation and replication operations for you, thereby realizing the deep copy of the object. We know that the same server can also achieve the deep copy of the object, why not do this? The root cause is the huge difference in efficiency, although clone () is very complicated, but there is no such thing as the object of reading and writing. With a Clone mechanism, you can create a copy of an object inside the method call, which is a local domain, and any of its operations will not affect the status of the original object. I personally think that this is very important to write a safe large program.