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 achieve Java Polymorphism

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

Share

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

This article focuses on "how to achieve Java polymorphism", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how Java polymorphism is realized.

Polymorphism is achieved by:

1 interface and implement the interface and override several different classes of the same method in the interface

Implemented by several different subclasses of the same method in the parent class and inheriting the parent class.

I. basic concepts

Polymorphism: send a message to an object and let the object decide what behavior to respond to. Dynamic method calls are implemented by assigning subclass object references to superclass object reference variables.

This mechanism of java follows a principle: when a superclass object references a variable that references a subclass object, the type of the referenced object rather than the type of the referenced variable determines whose member method is called, but the called method must be defined in the superclass, that is, the method overridden by the quilt subclass.

1. If an is a reference to class A, a can point to an instance of class A, or to a subclass of class A.

two。 If an is a reference to interface A, then a must point to an instance of a class that implements interface A.

Second, the mechanism of Java polymorphism.

In SUN's current JVM implementation mechanism, a reference to a class instance is a pointer to a handle, which is a pair of pointers:

A pointer points to a table, which actually has two pointers (one pointer to a method table that contains an object, and the other to a class object indicating the type to which the object belongs)

Another pointer points to a block of memory space allocated from the java heap.

III. Summary

1. Dynamic method invocation is realized by assigning subclass object references to superclass object reference variables.

DerivedC c2=new DerivedC (); BaseClass A1 = c2; / / BaseClass base class, DerivedC is a subclass inherited from BaseClass a1.play (); / / play () is defined in BaseClass,DerivedC, that is, the subclass overrides the method

Analysis:

1. Why can object instances of subclass types be overridden to superclass references?

Automatic upward transformation. Through this statement, the compiler automatically moves the subclass instance up to become the generic type BaseClass

2. Will a.play () execute the methods defined by the subclass or the parent class?

Subclass. At run time, the corresponding method is obtained based on the actual type referenced by the an object. That's why it's polymorphic. The object reference of a base class, which is assigned to different subclass object references, will behave differently when the method is executed.

In a1=c2, there are still two handles, A1 and c2, but A1 and c2 have the same block of data memory and different function tables.

2. You cannot assign a parent object reference to a subclass object reference variable

BaseClass a2=new BaseClass (); DerivedC C1 / error / error / error

In java, the upward transformation is automatic, but the downward transformation is not, we need to define and force it.

C1 = (DerivedC) a2; carry out forced transformation, that is, downward transformation.

3. Remember a very simple and complex rule that a type reference can only reference methods and variables contained in the type itself.

You may say that this rule is wrong, because when the parent class reference points to the subclass object, the method of the subclass is executed.

In fact, this is not contradictory, it is because of the use of late binding, dynamic runtime and according to the type to call the subclass method. If this method of the subclass is not defined in the parent class, an error will occur.

For example, the DerivedC class adds several functions (such as myFun ()) in addition to inheriting the functions defined in BaseClass.

Analysis:

When you use a parent class reference to point to a subclass, jvm already uses the type information generated by the compiler to adjust the conversion.

You can understand it this way, which is equivalent to making functions that are not contained in the parent class invisible from the virtual function table. Note that it is possible that some function addresses in the virtual function table have been rewritten in the subclass, so the virtual function item address in the object virtual function table has been set to the address of the method body completed in the subclass.

4. Comparison of polymorphism between Java and C++.

The solution for polymorphism in jvm is almost the same as in C++, except that many compilers in C++ put type information and virtual function information in a virtual function table, but use some technology to distinguish them.

Java separates type information from function information. After inheritance in Java, the subclass resets its own virtual function table, which has two parts of the project. Virtual functions inherited from the parent class and virtual functions of the subclass itself.

The virtual function call is called indirectly through the virtual function table, so it is possible to achieve polymorphism. All functions of Java, except those declared as final, are late-bound.

four。 1 behavior, different objects, they reflect in different ways

For example: method overloading overloading and method rewriting (overwriting) override

Class Human {void run () {output man running}} class Man extends Human {void run () {output man running} at this time, the same running, different objects, different (this is an example of method coverage) class Test {void out (String str) {output str} void out (int I) {output I}}

This example is method overloading, with the same method name and different parameter tables.

Ok, it's not enough to understand that it's not enough to use people to run for example.

Human ahuman=new Man ()

So I instantiated an object of Man and declared a reference to Human to point to the object Man.

It means that the object Man is regarded as Human.

For example, when you go to the zoo, you see an animal and don't know what it is. "what kind of animal is this?"this is a giant panda!"

These two sentences are the proof of *, because you don't know that it is a giant panda, but you know that its father is an animal, so it is reasonable for you to regard this giant panda object as its father. In this way, you should note that new Man (); does instantiate the Man object, so the output of the ahuman.run () method is "men are running." if you write some of its unique methods such as eat () under the subclass Man, and Human does not have this method, when calling the eat method, you must pay attention to cast (Man) ahuman. Eat (), so that you can.

For the interface, the situation is similar.

Example:

Package domatic; / / define superclass superA class superA {int I = 100; void fun (int j) {j = I; System.out.println ("This is superA");}} / / define subclass subB class subB extends superA {int m = 1 of superA; void fun (int aa) {System.out.println ("This is subB");}} / / define subclass subC class subC extends superA {int n = 1 of superA Void fun (int cc) {System.out.println ("This is subC");}} class Test {public static void main (String [] args) {superA a = new superA (); subB b = new subB (); subC c = new subC (); a = b; a.fun (100); a = c; a.fun }} / * * in the above code, subB and subC are subclasses of the superclass superA. We declare three reference variables a, b, and * c in the class Test to implement dynamic method calls by assigning subclass object references to superclass object reference variables. One might ask: * "Why don't (1) and (2) output: This is superA". * this mechanism of java follows a principle: when a superclass object references a variable to refer to a subclass object, * the type of the referenced object rather than the type of the referenced variable determines whose member method is called, * but the called method must be defined in the superclass, * that is, the method overridden by the subclass. * therefore, do not be confused by (1) and (2) in the above example, although it is written as a.fun (), because an in (1) is assigned by b, * points to an instance of the subclass subB, so (1) the fun () called is actually the member method fun () of the subclass subB, * it overrides the member method fun () of the superclass superA; similarly (2) calls the member method fun () of the subclass subC. * in addition, if the superclass inherited by the subclass is an abstract class, although the abstract class cannot be instantiated by the new operator, * you can create an object reference to the subclass object of the abstract class to achieve runtime polymorphism. The specific implementation method is the same as the above example. * however, the subclass of the abstract class must override all abstract methods in the implementation superclass, * otherwise the subclass must be modified by the abstract modifier and of course cannot be instantiated * /

Most of the above implement polymorphism by overriding the parent class with a subclass. Here is another way to implement polymorphism-overriding the parent method

There is no much inheritance in 1.JAVA, so a class can have a parent class. And the performance of inheritance is polymorphism. A parent class can have multiple subclasses, and the methods of the parent class (such as the method print ()) can be overridden in the subclass, so that the rewritten code in each subclass is different, so that the natural representation is different. In this way, if you use the variables of the parent class to reference different subclasses, you will get different results and representations when you call the same method print (). This is polymorphism, and the same message (that is, calling the same method) will have different results. Examples are as follows:

/ / parent class public class Father {/ / parent class has a child beating method public void hitChild () {}} / / subclass 1 public class Son1 extends Father {/ / override parent child beating method public void hitChild () {System.out.println ("Why hit me? what did I do wrong!") ;}} / / subclass 2 public class Son2 extends Father {/ / override parent spanking method public void hitChild () {System.out.println ("I know I'm wrong, stop typing!") ;}} / / subclass 3 public class Son3 extends Father {/ / override parent beating method public void hitChild () {System.out.println ("I run, you can't hit!") ;}} / / Test class public class Test {public static void main (String args []) {Father father; father = new Son1 (); father.hitChild (); father = new Son2 (); father.hitChild (); father = new Son3 (); father.hitChild ();}}

All called the same method, with different results! This is the expression of polymorphism!

At this point, I believe you have a deeper understanding of "how Java polymorphism is achieved". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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