java-多态

来源:互联网 发布:php hub 编辑:程序博客网 时间:2024/06/09 16:15

多态:

  • 一个对象具备多种形态。(父类的引用类型变量指向了子类对象)

多态的前提:

  • 必须存在继承或者实现关系。

  • 动物 a =new 狗();

多态要注意的细节:

  • 多态的情况下,子父类同名的成员变量时 ,访问的是父类的成员变量。
  • 多态的情况下,子父类存在非静态的成员函数时,访问的是子类的成员函数。
  • 多态的情况下,子父类存在静态的成员函数时,访问的是父类的成员函数。
  • 多态的情况下,不能访问子类特有的成员。

总结:

  • 多态情况下,子父类存在同名的成员时,访问的都是父类的成员,除了同名的非静态函数时,才是访问子类的。

  • 定义一个函数可以返回任意类型的图形对象。

//动物类abstract class Animal{    String name;    String  color = "动物色";    public Animal(String name){        this.name = name;    }    public abstract void run();    public static void eat(){        System.out.println("动物在吃..");    }}//老鼠class  Mouse extends Animal{    String color = "黑色";    public Mouse(String name){        super(name);    }    public  void run(){        System.out.println(name+"四条腿慢慢的走!");    }    public static void eat(){        System.out.println("老鼠在偷吃..");    }    //老鼠特有方法---打洞    public void dig(){        System.out.println("老鼠在打洞..");    }}class Fish extends Animal {    public Fish(String name){        super(name);    }    public  void run(){        System.out.println(name+"摇摇尾巴游..");    }}class Demo11 {    public static void main(String[] args)     {        /*        Mouse m = new Mouse("老鼠");        System.out.println(m.color);        //多态: 父类的引用类型变量指向子类的对象        */        Animal a = new Mouse("老鼠");        a.dig();        //a.eat();    }   }

多态的应用:

  • 多态用于形式参数类型的时候可以接受更多类型的数据。
  • 多态用于返回值类型的时候,可以返回更多类型的数据。
//图形类abstract class MyShape{    public abstract void getArea();    public abstract void getLength();   }class Circle extends MyShape{    public static final double PI = 3.14;    double r;    public Circle(double r){        this.r =r ;     }    public  void getArea(){        System.out.println("圆形的面积:"+ PI*r*r);    }    public  void getLength(){        System.out.println("圆形的周长:"+ 2*PI*r);    }}class Rect  extends MyShape{    int width;    int height;    public Rect(int width , int height){        this.width = width;        this.height = height;    }    public  void getArea(){        System.out.println("矩形的面积:"+ width*height);    }    public  void getLength(){        System.out.println("矩形的周长:"+ 2*(width+height));    }}class Demo12 {    public static void main(String[] args)     {        /*        //System.out.println("Hello World!");        Circle c = new Circle(4.0);        print(c);        Rect r = new Rect(3,4);        print(r);        */        MyShape m = getShape(0); //调用了使用多态的方法,定义的变量类型要与返回值类型一致。        m.getArea();        m.getLength();    }    //需求1: 定义一个函数可以接收任意类型的图形对象,并且打印图形面积与周长。    public static void print(MyShape s){ // MyShpe s = new Circle(4.0);        s.getArea();        s.getLength();    }    // 需求2: 定义一个函数可以返回任意类型的图形对象。    public static MyShape  getShape(int i){        if (i==0){            return new Circle(4.0);        }else{            return new Rect(3,4);        }    }}
0 0