多态**(Polymorphism)**
**1.**概念
多态 来自官方的说明
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
多态性的字典定义是指在生物学原理,其中的生物体或物质可具有许多不同的形式或阶段。 该原理也可以应用于面向对象的编程和Java 语言之类的语言。 一个类的子类可以定义自己的独特行为,但可以共享父类的某些相同功能。
从上面的描述中我们可以得出:继承、接口就是多态的具体体现方式。多态主要体现在类别、做事的方式上面。多态是面向对象的三大特征之一,多态分为编译时多态和运行时多态两大类。
**2.**编译时多态
方法重载在编译时就已经确定如何调用,因此方法重载属于编译时多态。
案例
计算任意两个数的和。
package com . we . polymorphism ;
public class Calculator {
public double calculate ( double a , double b ){
return a + b ;
}
public long calculate ( long a , long b ){
return a + b ;
}
}
package com . we . polymorphism ;
public class CalculatorTest {
public static void main ( String [] args ) {
Calculator c = new Calculator ();
long result1 = c . calculate ( 1 , 2 );
System . out . println ( result1 );
double result2 = c . calculate ( 1.0 , 2.0 );
System . out . println ( result2 );
}
}
**3.**运行时多态
The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
Java 虚拟机( JVM )为每个变量中引用的对象调用适当的方法。 它不会调用由变量类型定义的方法。这种行为称为虚拟方法调用,它说明了Java 语言中重要的多态性特征的一个方面。
package com . we . polymorphism . p1 ;
public class Father {
public void show (){
System . out . println ( "Father Show" );
}
}
package com . we . polymorphism . p1 ;
public class Child extends Father {
@Override
public void show () {
System . out . println ( "Child Show" );
}
}
package com . we . polymorphism . p1 ;
public class FatherTest {
public static void main ( String [] args ) {
//变量f 的类型是 Father
Father f = new Child ();
//f调用show() 时,不会调用 Father 定义的方法
f . show ();
}
}
案例
王者荣耀中英雄都有名字,都会攻击,物理英雄会发动物理攻击,法术英雄发动法术攻击。
package com . we . polymorphism . hero ;
public abstract class Hero {
protected String name ;
public Hero ( String name ) {
this . name = name ;
}
public abstract void attack ();
}
package com . we . polymorphism . hero ;
/**
* 物理英雄
*/
public class PhysicalHero extends Hero {
public PhysicalHero ( String name ) {
super ( name );
}
@Override
public void attack () {
System . out . println ( name + " 发动物理攻击 " );
}
}
package com . we . polymorphism . hero ;
/**
* 法术英雄
*/
public class SpellHero extends Hero {
public SpellHero ( String name ) {
super ( name );
}
@Override
public void attack () {
System . out . println ( name + " 发动法术攻击 " );
}
}
package com . we . polymorphism . hero ;
public class HeroTest {
public static void main ( String [] args ) {
Hero hero1 = new PhysicalHero ( " 赵云 " );
hero1 . attack ();
Hero hero2 = new SpellHero ( "甄姬 " );
hero2 . attack ();
}
}