Table of Contents
Java Basics Eleven - Polymorphism
1. Polymorphism Definition
2. Examples of polymorphic life
Home Java javaTutorial What is polymorphism? Polymorphic life examples

What is polymorphism? Polymorphic life examples

Jun 20, 2017 pm 03:35 PM
java Base Polymorphism

Java Basics Eleven - Polymorphism

1. Polymorphism Definition

Simply put: it is an object corresponding to different types.

Polymorphism in the code Reflection:
The reference of the parent class or interface points to the object of its subclass.

  1 /*  2   3 对象的多态性。  4   5 class 动物  6 {}  7   8 class 猫 extends 动物  9 {} 10  11 class 狗 extends 动物 12 {} 13  14  15  16 猫 x = new 猫(); 17  18 动物 x = new 猫();//一个对象,两种形态。 19  20  21  22 猫这类事物即具备者猫的形态,又具备着动物的形态。 23 这就是对象的多态性。 
 24  25 简单说:就是一个对象对应着不同类型.  26  27 多态在代码中的体现:
 28     父类或者接口的引用指向其子类的对象。 29  30  31 多态的好处: 32     提高了代码的扩展性,前期定义的代码可以使用后期的内容。 33  34 多态的弊端: 35     前期定义的内容不能使用(调用)后期子类的特有内容。通过向下转型来解决。 36  37 多态的前提: 38     1,必须有关系,继承,实现。(实现是特殊的继承) 39     2,要有覆盖。 
 40  41  42  43 */ 44  45 abstract class Animal 46 { 47     abstract void eat(); 48  49 } 50  51 class Dog extends Animal 52 { 53     void eat() 54     { 55         System.out.println("啃骨头"); 56     } 57     void lookHome() 58     { 59         System.out.println("看家"); 60     } 61 } 62  63 class Cat extends Animal 64 { 65     void eat() 66     { 67         System.out.println("吃鱼"); 68     } 69     void catchMouse() 70     { 71         System.out.println("抓老鼠"); 72     } 73 } 74  75 class Pig extends Animal 76 { 77     void eat() 78     { 79         System.out.println("饲料"); 80     } 81     void gongDi() 82     { 83         System.out.println("拱地"); 84     } 85 } 86  87  88  89 class DuoTaiDemo 
 90 { 91     public static void main(String[] args) 
 92     { 93          94 //        Cat c = new Cat(); 95 //        c.eat(); 96 //        c.catchMouse(); 97  98         Animal a = new Cat(); //自动类型提升,猫对象提升了动物类型。但是特有功能无法s访问。
 99                             //作用就是限制对特有功能的访问。
100                             //专业讲:向上转型。将子类型隐藏。就不用使用子类的特有方法。101 102 103 //        a.eat();104 105         //如果还想用具体动物猫的特有功能。 
106         //你可以将该对象进行向下转型。107 //        Cat c = (Cat)a;//向下转型的目的是为了使用子类中的特有方法。108 //        c.eat();109 //        c.catchMouse();110 111 //        注意:对于转型,自始自终都是子类对象在做着类型的变化。112 //        Animal a1 = new Dog();113 //        Cat c1 = (Cat)a1;//ClassCastException114 115 116         /*117         Cat c = new Cat();118 119 //        Dog d = new Dog();120 121 //        c.eat();122         method(c);123 //        method(d);124 //        method(new Pig());125         */126 127         method(new  Dog());128 129     }130 131     public static void method(Animal a)//Animal a = new Dog();132     {133         a.eat();134      //解决类型匹配问题的时候,我们就可以判断一下135         if(a instanceof Cat)//instanceof:用于判断对象的具体类型。只能用于引用数据类型判断
136 //                        //通常在向下转型前用于健壮性的判断。137 138         {139             Cat c = (Cat)a;140             c.catchMouse();141         }142         else if(a instanceof Dog)143         {144             Dog d = (Dog)a;145             d.lookHome();146         }147         else148         {149         150         }151         152     }153     /*154     public static void method(Cat c)155     {156         c.eat();157     }158     public static void method(Dog d)159     {    
160         161     }162     */    163 }
Copy after login

Upward transformation: The parent class reference points to the subclass object. Subclass-specific functionality is inaccessible.

Downcast: The subclass reference points to the parent class object.

1 Animal a = new Cat(); //自动类型提升,猫对象提升了动物类型。但是特有功能无法s访问。2                       //作用就是限制对特有功能的访问。3                       //专业讲:向上转型。将子类型隐藏。就不用使用子类的特有方法。4 5 Cat c = (Cat)a;//向下转型的目的是为了使用子类中的特有方法。
Copy after login

In practical applications, upward transformation facilitates code expansion (the code written before can be used in the future, only if it inherits or implements the base class), but the unique features of the subclass must be used When functional, it must be transformed downward.

Many times we cast upward to the Object class, and when our own unique functions are used, we cast downward and back.

2. Examples of polymorphic life

 1 /* 2 毕老师和毕姥爷的故事。 3 */ 4  5 class 毕姥爷 6 { 7     void 讲课() 8     { 9         System.out.println("管理");10     }11     void 钓鱼()12     {13         System.out.println("钓鱼");14     }15 }16 17 class 毕老师 extends 毕姥爷18 {19     void 讲课()20     {21         System.out.println("Java");22     }23     void 看电影()24     {25         System.out.println("看电影");26     }27 }28 29 30 31 32 33 class  DuoTaiDemo234 {35     public static void main(String[] args) 
36     {   //原来37 //        毕老师 x = new 毕老师();38 //        x.讲课();39 //        x.看电影();40      //多态41         毕姥爷 x = new 毕老师();42         x.讲课(); //这里讲的是Java的内容,Java把管理学覆盖了 43         x.钓鱼();44 45         毕老师 y = (毕老师)x;//ClassCastException46         y.看电影();47 48 49 50 51     }52 }
Copy after login

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

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles