search
HomeJavajavaTutorialWhat is polymorphism? Characteristics of polymorphism

What is polymorphism? Characteristics of polymorphism

Jun 21, 2017 pm 04:52 PM
javaBasememberFeatures

Java Basics 12 - Polymorphism is the characteristic of members

1. Characteristics

1, member variables.

Compilation and operation refer to the left side of the equal sign.

Overwriting only occurs on functions and has nothing to do with variables.

Fu f = new Zi();
System.out.println(f.num);//It is the parent class, the answer is 3

2, member function (non-static ).

Look at the left when compiling and the right when running.

Because member functions have overwriting characteristics.

Fu f = new Zi();//
f.show();
The output is the show method in the subclass

3, static function.

Look to the left for compilation and operation.

Static functions do not have polymorphism. Polymorphism is the polymorphism of objects, and static functions do not involve objects.

Fu f = new Zi();//
f.show();
The final output here is the content of the parent class’s show.

Zi z = new Zi();//
z.show();

The output is the show in the subclass

2. Example

  1 /*  2 多态时,  3 成员的特点:  4 1,成员变量。  5     编译时:参考引用型变量所属的类中的是否有调用的成员变量,有,编译通过,没有,编译失败。  6     运行时:参考引用型变量所属的类中的是否有调用的成员变量,并运行该所属类中的成员变量。  7     简单说:编译和运行都参考等号的左边。哦了。  8     作为了解。  9 覆盖只发生在函数上,和变量没关系。 10 Fu f = new Zi(); 11 System.out.println(f.num);//是父类,答案是3 12 没根据f的值(子类对象的地址)去找,而是根据f的类型去找。 13 开发时不可能出现这样的情况,我父类有了,我子类就直接拿来用了,而且用的时候一般都已经向下转型了。 14  15  16  17  18 2,成员函数(非静态)。 19     编译时:参考引用型变量所属的类中的是否有调用的函数。有,编译通过,没有,编译失败。 20     运行时:参考的是对象所属的类中是否有调用的函数。 21     简单说:编译看左边,运行看右边。 22  23     因为成员函数存在覆盖特性。 24 Fu f = new Zi();// 25 f.show(); 26 输出的是子类里面的show方法 27 依赖的是对象,有对象才有成员函数,必须动态的绑定到指定的对象上,所以运行的时候是看子类,而编译的时候检查语 28  29 法错误,所以编译的时候检查父类,所以看父类。 30 编译检查语法错误,运行时根据引用指向的地址运行。 31  32  33  34  35 3,静态函数。 36         编译时:参考引用型变量所属的类中的是否有调用的静态方法。 37         运行时:参考引用型变量所属的类中的是否有调用的静态方法。 38         简单说,编译和运行都看左边。 39  40         其实对于静态方法,是不需要对象的。直接用类名调用即可。 41 Fu f = new Zi();// 42 f.show(); 43 这里最后输出的是父类的show里面的内容,因为静态成员不需要对象,直接是被类名指向,都指向存静态方法的方法区, 44  45 而那个里面存的就是父类的show。 46 Zi z = new Zi();// 47 z.show(); 48 这里的zi是继承fu的,show方法是静态的 49 输出的是子类里面的show 50 其实可以理解为静态函数不具备多态性,多态性是对象的多态性,然后静态函数不涉及对象 51 父类对象引用,就是指向父类的静态函数 52 子类对象引用,就是指向子类的对象函数 53  54  55          56  57 */ 58  59 class Fu 60 { 61 //    int num = 3; 62     void show() 63     { 64         System.out.println("fu show"); 65     } 66  67     static void method() 68     { 69         System.out.println("fu static method"); 70     } 71 } 72  73 class Zi extends Fu 74 { 75 //    int num = 4; 76     void show() 77     { 78         System.out.println("zi show"); 79     } 80  81     static void method() 82     { 83         System.out.println("zi static method"); 84     } 85 } 86  87  88  89 class  DuoTaiDemo3 90 { 91     public static void main(String[] args) 
 92     { 93         Fu.method(); 94         Zi.method(); 95 //这个的实质是父类对象指向子类引用,就是有点像指针,f的值是子类对象的地址。 96         Fu f = new Zi();// 97 //        f.method();//输出是父类的静态 98 //        f.show();//编译的时候检查的是父类,运行的时候以子类为主,show被覆盖,运行的子类的show 99         //输出是子类的show,100 //        System.out.println(f.num);//是父类,答案是3101 102 103 //        Zi z = new Zi();104 //        System.out.println(z.num);//是子类,答案是4105     }106 }

3. Memory storage analysis

Fu f = new Zi();

Fu f defines a reference, which is a pointer, on the stack.

new Zi() defines an object in the heap, but this object has some members of the parent class.

1. If you use a subclass reference to point to this object, all access will be from the subclass.

2. If you use a parent class reference to point to this object, all access will be to the parent class in this object, but the parent class functions will be overwritten, so the members will be the parent class, and the functions will be Time subclass.

It must be based on the pointer type to access the things to be accessed. Cats must eat cat food, dogs must eat dog food.

The above is the detailed content of What is polymorphism? Characteristics of polymorphism. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software