• 多态性


    -----------siwuxie095

       

       

       

       

    多态性的体现:

    1)方法的重载与重写

    2)对象的多态性

       

       

    对象的多态性:

    1)向上转型:程序会自动完成

       

       

    2)向下转型:强制类型转换

       

       

       

       

    代码:

       

    package com.siwuxie095.pol;

       

    class A{

    public void tell1() {

    System.out.println("A---tell1()");

    }

    public void tell2() {

    System.out.println("A---tell2()");

    }

    }

       

    class B extends A{

    //复写方法 重写方法

    public void tell1() {

    System.out.println("B---tell1()");

    }

     

    public void tell3() {

    System.out.println("B---tell3()");

    }

    }

       

    public class PolDemo01 {

       

    public static void main(String[] args) {

    //向上转型

    B b=new B();

    A a=b; //或合成一步 A a=new B();

    //因为tell1() 是被重写的,所以调用时调用的是重写后的方法

    a.tell1();

    a.tell2();

     

    System.out.println();

     

    //向下转型

    A ax=new B();//向下转型一定要先发生向上转型

    B bx=(B)ax;

    bx.tell1();

    bx.tell2();

    bx.tell3();

     

    }

       

    }

       

       

    运行一览:

       

       

       

       

    如果在向下转型时不先发生向上转型,即 A ax=new A();,就会发生

    类型转换异常(ClassCastException),即 这两个类之间没有明确的

    指向关系

       

       

       

       

    多态性的应用:

       

    代码:

       

    package com.siwuxie095.pol;

       

    //父类 T

    class T{

    public void tell1() {

    System.out.println("W---tell1()");

    }

    }

       

    //子类 X

    class X extends T{

    public void tell2() {

    System.out.println("X---tell2()");

    }

    }

       

    //子类 Y

    class Y extends T{

    public void tell3() {

    System.out.println("Y---tell3()");

    }

    }

       

    //子类 Z

    class Z extends T{

    public void tell4() {

    System.out.println("Z---tell4()");

    }

    }

       

       

    public class PolDemo02 {

       

    public static void main(String[] args) {

    //子类执行父类方法

    say(new X()); //传递匿名对象进去

    say(new Y());

    say(new Z());

    }

     

    public static void say(T t) {

    t.tell1();

    }

       

    }

       

       

    运行一览:

       

       

       

       

       

    【made by siwuxie095】

  • 相关阅读:
    WorkFlow
    自己写的一个多线程的consumer 和 producter 模式
    Visual Studio进行Web性能测试
    基元线程同步——内核模式构造
    系统架构师
    《构建高性能的web站点》读书笔记缓存
    python中的代码对象
    python web框架互相融合, Pyramid或取代Django
    海量数据处理专题
    Django框架学习Forms篇
  • 原文地址:https://www.cnblogs.com/siwuxie095/p/6574929.html
Copyright © 2020-2023  润新知