多态性

多态分类:
  普通类多态 (静态方法没有多态性 ,成员变量没有多态性)

      

 1 package review07;
 2 /*
 3  *     多态的分类:
 4  *         普通类多态(静态方法没有多态性 ,成员变量没有多态性)
 5  *         抽象类多态(抽象父类的变量不能调用子类中特有的方法)
 6  *         接口多态
 7  * 
 8  *     多态的前提
 9  *         继承
10  *         方法重写
11  *         父类引用指向子类对象
12  * 编译时类型:引用数据类型定义时的类型就是编译时类型
13  * 运行时类型:程序运行时变量指向的正真对象的类型
14  */
15 //普通类多态
16 class Father4 {
17     int num = 10;
18     public void show(){
19         System.out.println("Father showw");
20     }
21     public static void method(){
22         System.out.println("Father method");
23     }
24     
25     
26 }
27 class Son4 extends Father4{
28     int  num =20;
29     public void show(){
30         System.out.println("Son4 show");
31     }
32     public void show1(){
33         System.out.println("Son4 show");
34     }
35     
36     public static void method(){
37         System.out.println("son4  method");
38     }
39 }
40 public class PolymorphismDemo2 {
41     public static void main(String[] args) {
42         Father4 f = new Son4();//向上造型  多态
43         f.show();//Son4 show
44         //f.show1();//父类引用不能调用子类中特有的方法
45         f.method();//Father method  静态方法没有多态性
46         System.out.println(f.num);//10  成员变量没有多态性
47     }
48 }
普通类多态


  抽象类多态(抽象父类的变量不能调用子类中特有的方法)

 1 package review07;
 2 /*
 3  * 抽象类多态
 4  */
 5 abstract class  Animal4{
 6     public abstract void show();
 7 }
 8 class Dog4 extends Animal4{
 9     public void show() {
10         System.out.println("Dog  show");
11     }
12 }
13 class Cat4 extends Animal4{
14     public void show(){
15         System.out.println("cat show()");
16     }
17     public void test(){
18         
19     }
20 }
21 //
22 public class PolymorphismDemo3 {
23     public static void main(String[] args) {
24         Animal4 an = new Dog4();
25         an.show();
26         
27          Animal4  a = new Cat4();
28          a.show();
29          //a.test();//抽象父类的变量不能调用子类特有的方法
30     }
31 }
抽象类多态


  接口多态     //接口不能调用子类特有的方法

 1 package review07;
 2 /*
 3  * 接口多态
 4  */
 5 interface Interf{
 6     public abstract void method();
 7 }
 8 class InterImple implements Interf{
 9     public void method(){
10         System.out.println("子类实现接口,重写method方法");
11     }
12     public void test(){
13         System.out.println("子类的test方法");
14     }
15 }
16 public class PolymorphismDemo4 {
17     public static void main(String[] args) {
18         Interf in = new InterImple();
19         in.method();
20         //in.test();//接口不能调用子类特有的方法
21     }
22 }
接口多态



多态前提:
  继承:
  方法重写
  父类引用指向子类对象

编译时类型:引用数据类型定义时的类型就是编译类型
运行时类型:程序运行时变量指向的真正对象的类型

原文地址:https://www.cnblogs.com/star521/p/8759931.html