• 面向对象--多态


    多态就是一开始模糊一点想象空间大点,真实现的时候再具体化。

    如何实现多态?

    编译时类型(模糊一点,一般是一个父类):由声明时类型决定。

    运行时类型(运行时,具体是哪个子类就是哪个子类)

    多态:吐过编译时类型和运行时类型不一致就会造成多态。

    就是程序的最终状态只有在执行过程中才被决定而非在编译期间就决定了。

    多态是方法的多态,属性没有多态性。

    多态存在的必要条件:继承,方法重写,父类引用指向子类对象

    示例:

    public  class Test{

    public static void main(String [] args){

    Animal animal=new Dog();//向上自动转型

    System.out.println(animal.age)//属性调用时,仍然是父类的属性,属性没有多态。

    animalCry(new Daog());

    //传的具体是哪个类就调用那一个类的方法。提高了扩展性

    animalCry(new Cat());

    Dog dog=(Dog) animal;//编写程序时,如果想调用运行时类型的方法,只能进行类型转换。

    dog.gnawBone();

    System.out.println(dog instanceof Animal);

    System.out.println(animal instanceof Cat);

    System.out.printla(animal instanceof Dog);

    }

    static void animalCay(Animal a){

    a.shout();

    }

    }

    class Animal{

    int age=;

    public void shout(){

    System.out.println("叫声")

    }

    }

    class Dog extends Animal{

    int age=20;

    public void shout(){

    System.out.println("汪汪汪")

    }

    }

    class Cat extends Animal{

    int age=15;

    public void shout(){

    System.out.primtln("喵喵喵");

    }

    }

  • 相关阅读:
    Allegro绘制PCB流程
    KSImageNamed-Xcode
    UIApplicationsharedApplication的常用使用方法
    javascript中间AJAX
    hdu1845 Jimmy’s Assignment --- 完整匹配
    嵌入式控制系统和计算机系统
    Bean行为破坏之前,
    jsonkit 分解nsarray 时刻 一个错误
    IO 字符流学习
    2013级别C++文章9周(春天的)工程——运算符重载(两)
  • 原文地址:https://www.cnblogs.com/javatask/p/6753603.html
Copyright © 2020-2023  润新知