Once again I know Java (a)----everything is Object

Source: Internet
Author: User

Suppose you have no object in reality. At least you will have a lot of objects in the Java world, and it sounds very exciting.

objects, references, classes and the real world

In the real world there are a lot of creatures, non-living creatures, jumping flies, the past of today's 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, and he knows his name age. Address.

Know what he likes to do. You want to describe this person in the Java language. What should you do?

This time. There is the concept of class.

Each class corresponds to something in the real world. For example, there are people 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 eats and walks, so we add ways to eat and walk in the "people" category.

When the world has ushered in a new life, we will be able to "new" a "person", "new" is called "Object".

When everyone 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. Sets the properties of the object. The method of manipulating the object.

This is the main object-oriented.

" things in the real world "-Abstraction--" class "-new-> " object " <-control-" reference "

Start by 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 non-constructive method 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 simply 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, very obvious. Put the constant.

In fact, we don't need to care about Java objects, where the variables exist. Because the JVM is going to help us with all this.

But I understand that. Help to improve our level.

When you run 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, this reference p points to the person object (in fact, the value of P is the memory address of the person object).

Such We interviewed by P. Then we get the memory address of the person and find the person object.

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.

This time. You change the state of the person object by P2, and you change the result of P. Because they point to the same object. (except for string.) will then be devoted to string)

At this time This is the case in memory:

Use a very popular way to explain references and objects.

Everyone should have used windows. Win has a wonderful thing called a shortcut.

Most of our desktop icons are shortcuts. It's not a running file (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.

Shortcuts cannot exist independently, nor can references exist independently (you can simply create a reference. But you have to assign a value to it when you want to use it. Otherwise it will be useless).

A file can have multiple shortcuts. The same object can have multiple references. and a reference can only be a corresponding object at the same time.

In Java, "=" cannot be considered an assignment statement. Instead of assigning an object to another object, the process essentially passes the address of the right object to the left reference, making the reference on the left point to the object on the right. There appears to be no pointer on the Java surface. But its reference is actually a pointer to the quality. In Java, the "=" statement should not be translated into an assignment statement, because it does not actually run a simple assignment process. Rather, it is a process of addressing the address, which is translated into an assignment statement that can cause a lot of misunderstanding and inaccurate translation.

Exceptions: Basic data Types

Why is there an exception? Since the objects created with the new operator will exist in the heap, the second in the heap to open up space and other behavior efficiency than the Operation Stack is lower. We usually create "small variables" when we write code. For example, int i = 1; If you use Interger to new one each time, the efficiency is not very high and the memory is wasted.

So for these situations. Java provides a "basic data type," which has eight common data types, and each base data type is stored on the stack. And their values are stored in the constant area.

To give a sample example:

int2;int2;

What we need to know is that in a constant area, the same constant will only exist. When you run the first sentence of code. Look for the constant area first to have no 2, no. Then opens up a space to store 2. Then deposit a variable i in the stack, let I point to 2;

When running the second sentence, find out that 2 already exists, so it doesn't open up new space. Save a new variable J directly in the stack. Let J point to 2.

Of course, each basic data type of the Java heap provides the appropriate wrapper class.

We can still create the variables we want with the new operator.

IntegernewInteger(1);IntegernewInteger(1);

However, the objects created with the new operator are different, that is, at this point, I and J point to different memory addresses. Because the new operator is called each time. will open 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'm going to put an integer source code (jdk1.8).

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 decorated with the final modifier. is a class that cannot be changed. Of course. After reading the Java source code, you will find that the basic types of wrapper classes are also modified by final. Here is an example of string.

Let's take a look at this example

Run the first sentence: constant area open space to store "ABC", s1 stored in the stack point to "ABC"

Running the second sentence, S2 also points to "ABC".

Run the third sentence, because "ABC" already exists, so direct point to it.

So three variables point to the same memory address, and the result is true.

When the S1 content changes. This time, the constant zone opens up a new space for "BCD", S1 points to "BCD", while S2 and S3 point to "ABC" so that only S2 and S3 are equal.

In such cases, S1,S2,S3 are string constants, similar to the basic data types. (Assuming that S1 = "abc" is running, the result will be true)

Let's look at another example:

Run the first line of code: Allocate space in the heap to hold a string object, open space in the constant area to hold the constant "ABC", the string object points to the constant. S1 points to the object.

Run the second line of code: S2 point to the string object in the previous step new.

Run the third line of code: Allocate 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's very obvious. S1 and S2 point to the same object

Then it was very strange, 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 above-mentioned literal, but a string object.

Because the string class is immutable. So the string object is also immutable. Each time we assign a string, we run a new string () and then point the variable to the new object instead of altering it on the original object.

Of course, Java also provides the StringBuffer class, which can be changed on the original object. Suppose you need to change the original object. Then please 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 look at a sample first:

This is a very classic example, we want to call the swap function, the values of A and B can be interchanged. But the truth is not. Why is that?

This is because Java is passed as a value. That is, when we call a function that needs to pass the reference, the number of the parameters passed to the function is not the number of references we pass in. But a copy of it. It's quite a mouthful, but the truth is that the principle is very easy. We can understand this:

A function of tangible participation. When the other function calls it. Data must be passed.
For example, the swap function must pass two integers to the other function to call swap.

At this time, there is a function to be unable to withstand loneliness, throw two integers over. However, the swap function is neat, it does not like to use other people's things. So it copied a copy of the number of references. The copied data is then modified to change. And the other people passed the number of participants did not move at all.

So, when the swap function is complete, the swapped data is just the copy of the swap itself. And the original data did not change.

Can also be understood as other functions to pass the data to the swap function of the shape, the last change is only the shape of the participation is not changed, so no matter what effect.

Let's look at a more complicated example (the person class adds the Get,set method):

Can see, we put P1 in, it has not been replaced with new objects. Because the change function does not manipulate the P1 reference itself, it is a copy of the reference.

You can still understand that the main function copies a copy of the P1 and then becomes the Chagne function, and finally points to the new person object that is the copy reference, and the actual participation P1 does not change.

Let's look at another example:

Why did you change it this time? Analyze it.

First of all. New a Person object, call Takoming. Then P1 pointed to xiaoming.

Xiao Ming 10 years old, with the passage of time, Xiao Ming's age to change, called a changgeage method. Put Xiaoming's citation in.

In the process of transmission, changgeage also have cleanliness. So copied a copy of Xiaoming'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 Xiao Ming this object has been changed, so all of Xiaoming's reference call method gets the age will change

So it changed.

Finally, a brief summary.

The process of passing the value of Java, in fact, is 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 reclaiming memory so that, despite its ease of use, the program no longer worries about memory as it does with C, but at the same time it is a disadvantage (not flexible enough).

In order to solve the problem that the memory operation is not flexible, we can adopt the method of soft reference.

Let's introduce these four types of references:

  • Strong references

    Most of the references we used were actually strong references. This is the most common reference to use.

    Suppose an object has a strong reference, it is similar to the indispensable necessities of life. The garbage collector will never recycle it. When there is not enough memory space, the Java virtual machine prefers to throw outofmemoryerror errors. Causes the program to terminate abnormally, and does not rely on arbitrary recycling of strongly referenced objects to resolve out-of-memory issues.

  • Soft references (SoftReference)

    Suppose an object has only soft references. It is similar to the items that can be found in the living things. Assuming that there is enough memory space, the garbage collector does not reclaim it, and if the memory space is insufficient, the memory of those objects is reclaimed. Just want the garbage collector not to recycle it. The object can be used by the program.

    Soft references can be used to implement memory-sensitive fast caches.

    Soft references can be used in conjunction with a reference queue (Referencequeue). Assuming that 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)

    Suppose that an object has only a weak reference, it is similar to a living thing that can have a product.

    The difference between a weak reference and a soft reference is that an object with only a weak reference has a more ephemeral 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. It's just that. Because the garbage collector is a very low-priority thread, it is not necessarily very fast to find objects that have only weak references.

    A weak reference can be used in conjunction with a reference queue (Referencequeue). Assuming that 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 the form of a dummy. is different from several other references. A virtual reference does not determine the life cycle of an object. Assuming that an object holds only virtual references, it is not the same as no reference. Can be garbage collected at all times.

    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, it is assumed that it also has a virtual reference, which adds the virtual reference to the reference queue associated with it before reclaiming the object's memory.

    The program is able to understand whether the referenced object will be garbage collected by inferring whether a virtual reference has been added to the reference queue. The program assumes that a virtual reference has been added to the reference queue, so 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 used frequently, and much more are soft references, as it accelerates 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 using new to create objects, Java is also able to copy objects through clone.

So what are the same and different ways of the two?

    • New

The new operator is intended to allocate memory.

When the program runs to the new operator, it first looks at the type following the new operator because it knows the type. Talent knows how much memory space to allocate.

After allocating memory, call the constructor, populate the object's various fields, this step is called the initialization of the object, after the construction method returns, an object is created, able to publish his reference (address) to the outside. The object can be manipulated externally by using this reference.


    • Clone

Clone in the first step is similar to new, is allocated memory. When you call the Clone method, the allocated memory and the source object (that is, the object that calls the Clone method) are the same. The respective fields in the original object are then used. Fills the domain of the new object, after the fill is complete. The Clone method returns, a new object is created, and the reference to the new object is also published externally.


How do you 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 and there is nothing wrong with stent cloning. 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. Suppose you don't understand. So look at this picture.

In fact, assuming just string is OK, because of the immutability of string, when you arbitrarily change a value, they will point to a different address, but except string, the others are mutable. This is a critical situation.

This is the case above. is shallow cloning.

Such a way of having references to other objects in your attribute list is actually very critical.

So, we need deep cloning. In other words, we need to clone a copy of the object in this object. How do you do it?

A copy of the byte stream in memory is easier 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 problem between the new object and the parent object, actually implementing a 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 the tool class simply implement the Serializable interface to clone the object without inheriting the Cloneable interface to implement the Clone () method.

Test:

Very 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 on a temporary, may be supplemented by the 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

Once again I know Java (a)----everything is Object

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.