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 Polymorphism in java from the Perspective of jvm

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

Today, I will talk to you about how to understand the polymorphism in java from the perspective of jvm. Many people may not understand it very well. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something from this article.

1. Recognizing polymorphism 1. Method invocation

In Java, there are two types of method calls, dynamic method calls and static method calls.

(1) static method call refers to the way to call the static method of the class, which is statically bound when the specific method is called at the time of compilation.

(2) dynamic method invocation needs the object affected by the method invocation, and the specific calling method is determined only when the method is called, which is dynamically bound.

The polymorphism we are talking about here is the latter-dynamic method calls.

2. The concept of polymorphism

There are two kinds of polymorphism: intra-class polymorphism and inter-class polymorphism. Let's first take a look at the standard concept: polymorphism is an important feature of object-oriented programming languages, which allows pointers or references of base classes to objects of derived classes and implements dynamic binding of methods during concrete access.

(1) Java method overloading (polymorphism between classes): you can create multiple methods in a class that have the same name but can have different parameter lists and return value types. Let's take an example to explain that a couple gave birth to multiple fetuses, which are similar in appearance, but are actually different children.

(2) Java method rewriting (polymorphism between parent and subclass): subclasses can inherit methods in the parent class, but sometimes subclasses do not want to inherit the methods of the parent class intact, but want to make certain changes, which requires method rewriting. Neither the overridden parameter list nor the return type can be modified. Let us give another example, that is, the son inherits his father's business, but the son has his own ideas and reinvests his father's estate.

2. Code implementation polymorphism 1. Polymorphism between classes: method overload public class SingleClass {

/ / Child 1:

Public String child () {

System.out.println ("child1")

Return "child1"

}

/ / Child 2: different from the number of parameters of Child 1

Public String child (String a) {

System.out.println ("child2")

Return "child2"

}

/ / Child 3: different from the order of child 4 parameters

Public String child (int aline string s) {

System.out.println ("child3")

Return "child3"

}

/ / Child 4: different from the order of child 3 parameters

Public String child (String sline int a) {

System.out.println ("child4")

Return "child4"

}

Public static void main (String [] args) {

/ / overloaded method calls: slightly

}

}

From the above code, we can see that there can be the same method name inside the class, but there is a unique parameter list. Of course, return types and modifiers can also be different. Let's take a look at the polymorphism between classes again.

2. Polymorphism between classes: method rewriting

There are actually two ways of polymorphism between classes: inheritance and interface. We explain the two ways one by one.

(1) inheritance to achieve polymorphism

We use an example to explain the way of inheritance. for example, the father can have the right to deal with his own house, and the son can also inherit the father's business.

Step 1: define the parent class

Public class Father {

Public void dealHouse () {

System.out.println ("Father disposes of the property")

}

}

Step 2: define subcategories (eldest son and youngest son)

/ / the eldest son

Public class SonA extends Father {

@ Override

Public void dealHouse () {

System.out.println ("the eldest son disposes of the property")

}

}

/ / youngest son

Public class SonB extends Father {

@ Override

Public void dealHouse () {

System.out.println ("the youngest son disposes of the property")

}

}

Step 3: test

Public class Test {

Public static void main (String [] args) {

Father father=new Father ()

Father sonA=new SonA ()

Father sonB=new SonB ()

Father.dealHouse ()

SonA.dealHouse ()

SonB.dealHouse ()

}

}

/ / the father disposed of the property

/ / the eldest son disposes of the property

/ / the youngest son disposes of the property

(2) Polymorphism is realized by interface.

The inheritance method of the interface is actually the same as above, except that the parent class is turned into an interface, and the other content is only changed with a smile. Here we will not demonstrate it, but only the form of the parent interface is given here.

Public interface Father {

Public void dealHouse ()

}

At this point, we basically demonstrate the implementation of polymorphic code, and the case is relatively simple, but it is not enough for us to understand the idea of polymorphism. the most important thing is to analyze it from the perspective of virtual machine.

Third, analyze polymorphism

In order to analyze polymorphism in depth, we need to figure out several problems.

1. Jvm memory

As we have seen in the above code, the names of these methods are actually the same, whether they are polymorphisms within classes or polymorphisms between classes, so how does the underlying virtual machine distinguish when our program is running (java virtual machine implements dynamic calls)? For this reason, let's start with the java virtual machine.

In fact, when the java virtual machine executes the java program, it does not run directly. It needs a process. Let's take a look at it with a picture:

The picture above is clear, that is, to run our java file, we need to compile it into a .class file through the java compiler, then load the .class file into JVM through the class loader, and then execute it. And JVM is divided into five areas, so where are the polymorphic methods defined in the code stored? To do this, we also need to do an analysis of this area of memory:

I have given a map of the runtime data partition of java7, and I am sure you can see the basic situation of each area. So where exactly does our polymorphic approach exist? Yes, it is the latter method area. Java stores the instance objects we have created, while the method area stores the type information of the class.

And the type information in this method area is different from the class object stored in the heap. In the method area, there is only a unique instance of the type information for this class (so the method area is the memory area shared by each thread), while there can be multiple class objects in the heap. In other words, the type information of the method area is like a template, and those class objects are like instances created from these templates.

2. Analyze through examples.

Now let's use the above example to illustrate how polymorphism is implemented in the java virtual machine. There are two lines of code in the test class:

Father sonA=new SonA ()

Father sonB=new SonB ()

Polymorphism occurs when the program runs to Father sonA=new SonA (), because you see Father at compile time, but at run time new comes out a SonA class, and the two types are not the same. So how is the code saved in memory at run time?

(1) Father sonA is a reference type that exists in the local method table in the java stack.

(2) new SonA actually creates an instance object and stores it in the java heap.

(3) the type data of SonA exists in the method area.

Let's take a look in memory:

What is stored in reference is the actual address of the object in the heap, and the object information stored in the heap contains the corresponding type data in the method area. The process is simple, let's sort it out:

Step 1: the virtual machine queries the local variable table in the java stack through reference (reference to Father) to get the pointer of the object type data in the heap

Step 2: find the object type data in the method area through the pointer to the object

Step 3: query the method table to run the method of the actual class (SonA class).

Well, by the third step, we know that it is actually through the method table to locate the actual running method. Let's take a look at what this method table is.

3. Method table

The method table must exist in the method area, and it is the key to implementing polymorphism, where references to instance methods are saved and directly referenced. The java virtual machine uses this method table to determine which polymorphic method to run when executing the program.

Using the above example, we demonstrate how the parent and child classes are saved in the method table:

It is obvious that every class has a method table, and different methods in the subclass point to different type information. Those inheriting from Object point to Object, and those inheriting from Father point to Father (that is, the method dealHouse that contains the parent class).

Maybe we are confused at this point, since the dealHouse method of the subclass is actually the Father of the parent class, why do we execute the dealHouse method of the subclass? Don't worry. Look down. This is the essence of the java virtual machine distinguishing polymorphic methods (implementing dynamic invocations).

When the method table of the Son class has a pointer to the dealHouse method of the Father class, as well as a pointer to its own dealHouse method, the new data will overwrite the original data, that is, the reference to Father.dealHouse will be replaced with a reference to Son.dealHouse (occupying the position in the original table)

Note:

What is described above is actually an analysis of the polymorphism of the inheritance implementation, and there will be a different understanding of the interface implementation.

The Java virtual machine invokes the interface method by searching the method table. For example, to find the dealHouse () method in the method table of the Father interface, you must search the entire method table of Father. In terms of efficiency, the invocation of interface methods is always slower than that of class methods.

After reading the above, do you have any further understanding of how to understand polymorphism in java from a jvm perspective? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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

Internet Technology

Wechat

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

12
Report