Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand objects in Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "how to understand the objects in Java". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Heap (heap) and stack (stack)

A heap is a piece of memory used to store objects

The stack is another piece of memory that executes methods and stores local variables, following the principle of last-in, first-out

PS: the stack does not store the method, it just executes the method. After the method is executed, the method will be popped off the stack (the method exists in the method area)

Let's use the actual code to look at the difference between the stack and the stack.

The code is as follows:

Public class LiveAndDeathDemo {/ / basic type properties private int a; public static void main (String [] args) {LiveAndDeathDemo live = new LiveAndDeathDemo (1); live.fun ();} public void fun () {int temp = 10; System.out.println (temp);} public LiveAndDeathDemo (int a) {this.a = a } public int getA () {return a;} public void setA (int a) {this.a = a;}}

As you can see, there is an instance variable a (heap), two methods main and fun, where fun has a local variable temp (stack)

The differences are as follows:

栈 堆

Here is a brief introduction to the above process.

The main method is pushed into the stack to create the local variable live (reference to the object)

Create an object live, open up memory in the heap, and put live into the heap

Live calls the fun method to push the fun onto the stack (when fun is at the top of the stack)

Fun execution is complete, off the stack, continue to execute the main method

Finally, the execution of the main method is completed, it is also out of the stack, and the program ends.

Some friends here may want to ask, what if the property is a reference? Where is it going to be stored?

Heap

The reference is stored in the heap, and the object that the reference points to is also stored in the heap, just another place in the heap

As shown in the following figure: the property liveRef of the live object in the heap points to another object (live object 2)

Why introduce heaps and stacks first?

Because heaps and stacks are closely related to the lives of objects.

If people are compared to objects, the pile is people's home, and the stack is the outside world.

We were born at home, dealing with the outside world, and finally at home.

Creation of objects (health)

It is a question of survival or destruction.

Shakespeare's Hamlet

In Java's fancy world, it's also a question, but it's a question with an answer.

The answer is down there.

Let's simplify the problem here.

Because our most common creation object is created through new, and the core of new object is realized through constructor, so we focus on constructor for simplicity, and the rest will be introduced later in the virtual machine section.

Classification of constructors:

No-parameter constructor

Parametric constructor

The difference between a constructor and a normal method:

Constructor has no return type

The constructor name is the same as the class name

About the default actions of the compiler:

If no constructor is defined, the compiler creates a no-argument constructor by default

If the subclass defines a parameterized constructor and the constructor that calls the parent class is not displayed, the compiler calls the parent class's parameterless constructor by default

When you have your own create constructor (with or without parameters), the compiler will no longer create the constructor.

Overloading of the constructor:

It is commonly used to set the default value of a property

The specific way is to call multiple constructors layer by layer (nesting dolls again)

Here's an example:

Public class LiveAndDeathDemo {private int a; private String name; public LiveAndDeathDemo () {this (1);} public LiveAndDeathDemo (int a) {this (a, "JavaLover");} public LiveAndDeathDemo (int a, String name) {this.a = a; this.name = name;} / / omit getter,setter}

If expressed in a picture, it looks like this.

构造函数 调用层级

Privatization of constructor

If the constructor is privatized, how do you use it?

Privatization indicates that only the class itself can be called, which is mainly used in factory methods

For example, the source code of LocalDate in Java is as follows:

Public final class LocalDate implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable {/ / Constructors privatize private LocalDate (int year, int month, int dayOfMonth) {this.year = year; this.month = (short) month; this.day = (short) dayOfMonth } / / provide a static method to create object instances public static LocalDate of (int year, int month, int dayOfMonth) {YEAR.checkValidValue (year); MONTH_OF_YEAR.checkValidValue (month); DAY_OF_MONTH.checkValidValue (dayOfMonth); return create (year, month, dayOfMonth);}}

This usage is often used in LocalDate as a tool class, as well as singleton patterns (which will be introduced later in the design pattern)

The constructor described above is not introduced to the parent class, so let's start with

If there is a parent class, what is the difference between the constructor

This and super:

Before introducing the constructor of the parent class, it is necessary to introduce this super

This points to the current class

Super points to the parent class

Super is used to explicitly call parent-related properties and methods (including constructors)

For example, super.filedA, super.fun (), etc.

Here is a special case. If you are in the constructor of a subclass or in an overridden method, you can call the constructor or method corresponding to the parent class by calling super () directly (demonstrated in the following code)

The execution order of the constructor

If the subclass Dog inherits the parent class Animal, the constructor of the parent class is called first, and then the constructor of the subclass is called

If there is a parent class above the parent class Animal, it will continue to call the

The above process is called "constructor chain"

This relationship is a bit like: the relationship between children and parents, if children want to be born, they must first let their grandparents give birth to their parents before parents can have children.

So here if we want to construct a subclass, we must first construct the parent class; if the parent class has a parent class, we continue to extend until the Object superclass

The following code demonstrates the process of this layer-by-layer call:

Public class SuperDemo extends Father {public SuperDemo () {/ / 1.1This shows that the constructor calling the parent class / / 1.2 Super must be placed on the first line of the constructor super (); System.out.println ("sub construct");} public static void main (String [] args) {SuperDemo demo = new SuperDemo () }} class Father {public Father () {/ / 2. The constructor that calls the parent class (Object) is not shown. The compiler will call System.out.println ("father construct") itself;}} / * * assume that the following Object is our superclass class Object {public Object () {/ / 3. The final constructor will be adjusted to this end.

The output is as follows:

Father constructsub construct

As you can see, first call the constructor of the parent class Father, and then call the constructor of the subclass

The inheritance relationship between them is as follows:

SuperDemo的继承关系

The illustration shows:

The dotted line on the left indicates that it is called up layer by layer until the superclass Object

The implementation on the right indicates that the completion of the above construction will go back to the lower layer and continue to build until the current class

Well, this is roughly what the construction process looks like, and there are a lot of other details (such as class initialization, etc.). It's not going to be introduced here, it's too much, let's introduce it later.

Collection (extinction) of objects

Object collection is an operation to release useless objects (recyclable) when the program is out of memory, which is done by the garbage collector GC

What is a useless object?

Useless objects are recyclable objects.

Human talk: when the last reference to object A ref disappears, object A becomes a useless object, waiting for the garbage collector to collect

Then how does the citation disappear?

There are basically two situations:

If the reference is a local variable, the reference will be released when the method in which the reference is located finishes, and the object will then be marked as useless, waiting to be recycled

When a reference points to another object or null, the object is marked as useless, waiting to be recycled

It is all assumed that the reference is the last reference to the object. If there are multiple references to the same object, the object will not be marked as recyclable, that is, useless, until all the references disappear.

Summary

Stack and stack

The heap holds objects, and the stack is used to execute methods and store local variables

Creation of object

It is mainly created through constructors, such as new objects

If you are deserializing to create an object, it will not be constructed, because after construction, the properties of the object will be reinitialized and the serialized property values will be erased (the IO stream in the previous Java is involved)

If the subclass has a parent class, the constructor of the parent class is called first. If the parent class has a parent class, so on until the Object superclass

Collection of objects

When the last reference to the object disappears, the object becomes a useless object, waiting for the garbage collector to collect

That's all for "how to understand objects in Java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report