If you have no object in reality, at least you will have a lot of objects in the Java world, do you sound excited?
objects, references, classes and the real world
In the real world there are so many creatures, non-living creatures, running jumping flies, past present future, dazzling. The purpose of our programming is to solve real-life problems. So inevitably we have to deal with all kinds of strange things in the real world.
In the real world, you have a new acquaintance with a friend, you know what he looks like, he knows his name, his age, his address. Know what he likes to do. You want to describe this person in the Java language, what should you do?
At this time, there is the concept of the class. Each class corresponds to something in the real world. Like someone in the real world. Then we'll create a class about "people".
Everyone has a name, there are addresses and so on personal information. Then we'll add these attributes to the "People" class.
Everyone will eat and walk, then we will add a way to eat and walk in the "People" class.
When the world has ushered in a new life, we Can "new" a "person", "new" comes out is called "Object".
Each person is born, the parents will give him a name. In the program, we need a way to manipulate the "object", so there is a reference. We manipulate objects by reference, set the properties of the object, and manipulate the object's methods.
This is the most basic object-oriented.
" things in the real world "-Abstraction--" class "-new-> " object " <-control-" reference "
starting from creating an object
The premise of creating an object is to have a class first. Let's start by creating a person class ourselves.
//Person类publicclass Person { private String name; privateint age; publicvoideat(){ System.out.println("i am eating"); }}
Creates a person object.
new Person();
How to understand this simple code?
- New Person: An object of type person
- () : This parenthesis is equivalent to a parameterless constructor that calls the person
- P : reference to Person object
Some people will think that P is the new person object. This is a false understanding that P is just a reference to a person object. So the question comes, what is a quote? What is the object again? This is going to start with memory.
procedures for creating objects
Java generally divides memory into four areas: heap, stack, static zone, constant area.
- Heap: In RAM, for storing all Java objects.
- Stack: In RAM, the reference exists on the stack.
- Static zone: In RAM, variables modified by the static modifier are placed here
- Constant area: In ROM, it is obvious that the constant is placed.
In fact, we don't need to care about Java objects, where the variables exist, because the JVM will help us with that. But understanding this helps to improve our level.
When executing this code.
new Person();
First, it creates a space in the heap to hold the new person object. Then, a reference p is created, stored in the stack, and the reference p points to the person object (in fact, the value of P is the memory address of the person object).
In this way, we find the person object by accessing p and then getting the memory address of the person.
And then there's this code:
Person p2 = p;
The meaning of this code is:
A new reference is created, saved in the stack, and the referenced address also points to the person's address. At this point, you change the status of the person object by P2, and you change the result of P. Because they point to the same object. (except for string, which is then dedicated to string)
At this point, this is the case in memory:
Use a very popular way to explain references and objects.
Everyone should have used windows. Win has a magical thing called a shortcut. Most of our desktop icons are shortcuts. It's not an executable (not an. exe file) of the app that we installed on the computer, so why click on it to open the app? I don't have to talk about that.
Our objects and references are the same as the shortcuts and the files that they connect to.
Instead of manipulating files directly, we use shortcuts to manipulate them. A shortcut cannot exist independently, nor can a reference exist independently (you could just create a reference, but you have to assign it when you want to use it, otherwise it will be useless).
A file can have multiple shortcuts, and the same object can have multiple references. A reference can only correspond to one object at a time.
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 seems to be no pointer on the Java surface, but its reference is essentially a pointer. In Java, the "=" statement should not be translated into an assignment statement, because it does not perform a simple assignment process, but rather a process of addressing the address, and being translated into an assignment statement can cause many misunderstandings and inaccurate translations.
Exceptions: Basic data Types
Why is there an exception? Because objects created with the new operator will exist in the heap, and the second in the heap to open up space and other behavioral efficiency is lower than the Operation Stack. When we write code, we often create "small variables" such as int i = 1, and if you use Interger to new one each time, the efficiency is not very high and the memory is wasted.
So for these cases, Java provides a "basic data type," a total of eight basic data types, each of the basic data types are stored in the stack, and their values are stored in the constant area.
As an example:
int2;int2;
What we need to know is that in a constant area, the same constant will only exist for one. When you execute the first sentence of code. First find the constant area there is no 2, no, then open a space to store 2, and then put a variable i in the stack, let I point to 2;
When the second sentence is executed, the search finds that 2 already exists, so it does not open up new space. Save a new variable J directly on the stack and let J point to 2;
Of course, each basic data type in the Java heap provides the corresponding wrapper class. We can still create the variables we want with the new operator.
IntegernewInteger(1);IntegernewInteger(1);
However, objects created with the new operator are different, that is, at this point, I and J point to different memory addresses. Because each call to the new operator opens up new space in the heap.
Of course, when it comes to basic data types, you have to mention Java's classic design.
Look at the code first:
Why is a true one is false?
I will not speak, should know. I would like to put an integer source (jdk1.8) it.
The inside of the Integer class defines an inner class that caches all numbers from 128 to 127, so you know.
Another exception: String
String is a special class, because it is modified by the final modifier, and is a class that cannot be changed. Of course, after reading the Java source code, you will find that the basic types of the various packaging classes are also modified by the final. Here is an example of string.
Let's look at an example like this
Execution of the first sentence: the constant area of space to store "ABC", s1 stored in the stack point to "ABC"
To execute the second sentence, S2 also points to "ABC",
Execute the third sentence, because "ABC" already exists, so point it directly.
So three variables point to the same memory address, and the result is true.
When the S1 content changes. This time, the constant area opens up new space for "BCD", S1 points to "BCD", while S2 and S3 point to "ABC" so only S2 and S3 are equal.
In this case, S1,S2,S3 are string constants, similar to the base data type. (If the S1 = "abc" is executed, the result will be true)
Let's look at one more example:
Executes the first line of code: Allocates space in the heap to hold a string object, opens up space in the constant area to hold the constant "ABC", the string object points to the constant, and S1 points to the object.
Executes the second line of code: S2 points to "ABC"
Executes the third line of code: Allocates a new space in the heap to hold the string object, the new object points to the constant "ABC", and S3 points to the object.
Here, it is clear that S1 and S2 point to the same object (although two string objects point to the same constant, but two objects are different)
Then it was very weird, we let S1 still = "abc", but the result S1 and S2 point to the address is different.
What's going on here? This is what is special about the string class, the new string is no longer the string constant above, but the string object.
Because the string class is immutable, the string object is also immutable, and each time we assign a string to a value is the equivalent of executing a new string (), and then having the variable point to it, rather than modifying it on the original object.
Of course, Java also provides the StringBuffer class, which can be modified on the original object. If you need to modify the original object, then use the StringBuffer class.
value passing and reference passing the war
Is Java a value pass or a reference pass? There is no doubt that Java is a value-passing. So what's called value passing and reference passing?
Let's first look at an example:
This is a classic example, we want to call the swap function, the values of A and B can be interchanged, but in fact there is no. Why is that?
This is because Java is passed by value. That is, when we call a function that needs to pass arguments, the arguments passed to the function are not the parameters that we pass in, but the copy. That's a bit of a mouthful, but the principle is simple. We can understand this:
A function of a tangible parameter that must be passed when another function calls it.
For example, the Swap function, the other function to call swap must pass two integers to come over.
This time, there is a function according to endure loneliness, throw two integers come over, but, the swap function is neat, it does not like to use other people's things, so it passed over the parameters copied a copy, and then the copy of the data repair modification, and the other people passed the parameters of the move did not move at all.
So, when the swap function is finished, the swapped data is just the copy of the swap itself, and the original data does not change.
It can also be understood that the data is passed to the parameter of the SWAP function for other functions, and the last change is only the formal parameter and the argument is not changed, so it will not have any effect.
Let's look at a more complicated example (the person class adds the Get,set method):
As you can see, we pass the P1 in, and it is not replaced with new objects. Because the change function does not manipulate the P1 reference itself, it is a copy of the reference.
As you can still understand, the main function copies a copy of the P1 and then becomes the formal parameter of the Chagne function, which ultimately points to the copy reference of the new Person object, and the argument P1 does not change.
Let's look at one more example:
Why did you change it this time? Analyze it.
First of all, new a person object, call Takoming bar. Then P1 pointed to xiaoming.
Xiao Ming 10-year-old, with the passage of time, Xiao Ming's age to change, called a changgeage method, the reference of Xiaoming passed in.
The process of transmission, Changgeage also has a neat, so copied a copy of Xiao Ming's reference, this copy also points to Xiao Ming.
Then changgeage through his own copy of the reference, changed the age of Xiaoming.
Because it is xiaoming, this object has been changed, so all of Xiaoming's reference calling method gets the age of change
So it changed.
Finally, a brief summary.
The process of passing a value in Java is actually a copy, whether it is a variable or a reference. So, don't expect to pass a variable to a function to change the variable itself.
strong references to objects, soft references, weak references, and virtual references
In Java, the JVM is responsible for allocating and recycling memory, so that while it is easy to use, the program does not have to worry about memory as much as C, but it is also a disadvantage (inflexible). In order to solve the problem that memory operation is not flexible, we can adopt soft reference method.
Let's introduce these four types of references:
-
Strong references
Most of the references we used before are actually strong references, which are the most common references. If an object has a strong reference, it is similar to essential necessities, and the garbage collector will never recycle it. When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues.
-
Soft references (SoftReference)
If an object has only soft references, it is similar to a living thing that can be used. If the memory space is sufficient, the garbage collector does not reclaim it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.
A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is garbage collected, the Java Virtual machine will add the soft reference to the reference queue associated with it.
-
Weak references (WeakReference)
If an object has only weak references, it is similar to a living thing that can be used. The difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.
A weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it.
-
Virtual Reference (Phantomreference)
"Virtual Reference", as the name implies, is a dummy, unlike several other references, a virtual reference does not determine the object's life cycle. If an object holds only virtual references, it can be garbage collected at any time, just as there are no references.
Virtual references are primarily used to track the activities of objects that are garbage collected. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is recycled.
In the actual development, weak references and virtual references are not commonly used, more often soft references, because it can accelerate the recovery of the JVM.
How soft references are used:
As for soft references, I'll write a separate article later, so here's the first one.
Replication of Objects
In addition to creating objects with new, Java can also copy objects by using clone.
So what are the similarities and differences between these two approaches?
The new operator is intended to allocate memory. When the program executes to the new operator, it first looks at the type following the new operator because it knows the type to know how much memory space to allocate. After allocating memory, call the constructor, populate the object's fields, this step is called the initialization of the object, after the construction method is returned, an object is created, you can publish his reference (address) to the outside, you can use this reference to manipulate the object externally.
Clone in the first step is similar to new, is to allocate memory, when calling the Clone method, the allocated memory and the source object (that is, the object called the Clone method) is the same, and then use the corresponding fields in the original object, populate the new object's domain, after the completion of the Clone method returns, A new, identical object is created, and the reference to the new object can be published externally.
How to use Clone to get an object?
Look at the code:
Made some changes to the person class.
Look at the implementation code:
This gives you the same new object as the original.
deep copy and shallow copy
However, careful and thoughtful people may find a problem once.
Age is a basic data type, there is no problem with the stent clone, but name is a string type. is the name of the object after our clone and the name of the original object pointing to the same string constant?
Do an experiment:
Sure enough, it's the same object. If you don't understand, look at this picture.
In fact, if just string is OK, because of the immutability of string, when you arbitrarily modify a value, they will point to a different address, but except string, the others are mutable. It's dangerous.
In this case, it is a shallow clone. This is a dangerous way to have references to other objects in your property list. So, we need deep cloning. In other words, we need to clone a copy of the object in this object as well. How do you do it?
A copy of the byte stream in memory is relatively easy to implement. Write the parent object into a byte stream and read it out of the byte stream so that a new object can be created, and there is no reference sharing between the new object and the parent object, actually implementing the deep copy of the object.
//The object that uses the tool class must implement the Serializable interface, otherwise there is no way to implement cloning. Public classcloneutils { Public Static<t extends Serializable> TClone(T obj) {T Cloneobj =NULL;Try{//write byte streamBytearrayoutputstream out=NewBytearrayoutputstream (); ObjectOutputStream Obs =NewObjectOutputStream ( out); Obs.writeobject (obj); Obs.close ();//Allocate memory, write to original object, generate new ObjectBytearrayinputstream iOS =NewBytearrayinputstream ( out. Tobytearray ()); ObjectInputStream Ois =NewObjectInputStream (iOS);//Returns the generated new objectCloneobj = (T) ois.readobject (); Ois.close (); }Catch(Exception e) {E.printstacktrace (); }returnCloneobj; }}
Objects that use this tool class can implement cloning of objects as long as the Serializable interface is implemented, without inheriting the Cloneable interface to implement the Clone () method.
Test it:
It's perfect.
This time, the person class implements the Serializable interface
Whether to use replication, deep copy or shallow copy to see the situation to use.
About serialization and deserialization will be spoken later.
This article is here for the moment, the following supplementary words I will continue to add, there are mistakes, I will promptly correct. You are welcome to ask questions.
Blog Sync Update at http://blog.improvecfan.cn
Case code placed in Github:https://github.com/cleverfan/javaimprove
A re-understanding of Java (i)----objects of all things