Granda's Blog

JAVA:多态浅析

多态

  • 多态的定义:指允许不同类的对象对同一消息做出响应。即同一消息可以根据发送对象的不同而采用多种不同的行为方式。
  • 多态的作用:消除类型之间的耦合关系

多态存在的条件

  1. 继承
  2. 重写
  3. 向上转型(upcasting):父类引用指向子类对象

JAVA中的多态

  • 如果编译时的类型和运行时的类型不一样,就会出现多态

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    class FatherClass{
    public void teach(){
    System.out.println("This is father's teach method");
    }
    public void test(){
    System.out.println("This is the method that will be overwrote by son");
    }
    }
    class SonClass extends FatherClass{
    public void eat(){
    System.out.println("This is the son's eat method");
    }
    public void test(){
    System.out.println("This is the son's test method,which will overwrite the father's test method");
    }
    public static void main(String[] args){
    //编译时类型是FatherClass,运行时类型是SongClass,发生多态
    FatherClass man = new SonClass();
    man.test();//执行的是子类重写的test方法
    man.eat();//该语句编译不通过,编译时man对象是FatherClass类型,不存在eat()方法
    //但是引用变量在运行时确实包含eat()方法,可以通过反射来执行该方法
    }
    }
  • 多态性主要是体现在实例方法的重写上,对象的实例变量不具备多态性

  • 引用变量在编译时只能够调用其编译时类型具备的方法,但运行时可以运行它运行时类型具备的所有方法
  • 通过引用变量来访问包含的实例变量时,总是试图访问它编译时类型所定义的成员变量,而不是它运行时类型定义的成员变量