1.多态
       1.1多态:一个失误的多种形态
       1.2多态的表现
        行为(方法)多态:重写和重载
        引用多态(动态绑定):编译时的类型和运行时不一致的这种现象
                     动态绑定
        注意:引用多态存在继承关系

        自动类型转换
        char c=10;
        int a=c;

        强制类型转换    
        int a=10;
        char c=(char)a;

        向上转型
        父类=子类;
        Pet p = new Dog();

        向下转型
        子类 =(子类)父类;
        Dog d=(Dog) p;
        
        注意:java.lang.ClassCastException:类型转换异常
            父类的运行时类型跟要转成的子类的类型不一致

    1.3 多态【子类就是父类】
         为什么使用多态:
        提高程序可扩展性,可维护性,提高代码可重用性

        什么是多态:
        具有表现多种形态能力的特征 同一个实现接口,使用不同的实例而执行不同的操作          

    1.4实现多态的两种形式:
         a.使用父类作为方法形参实现多态
         public void play(F p){...};

         b.使用父类作为方法返回值实现多态
         public F getF(int type){...};

//子类,圆形
public class Circular extends Graph {
        private final double X=3.14;        //半径
        
        public Circular(double r){
            super(r);
        }
        
        public void getArea(){
            double m=(super.getLen()*X*X);
            System.out.println("圆的半径为"+super.getLen()+"\n面积为"+m);
        }


//子类,长方形
public class Rectangle extends Graph {
    private double weight;            //宽度
    
    public  Rectangle(double len,double weight){
        super(len);
        this.weight=weight;
    }
    
    public double getWeight(){
        return weight;
    }
    
    public void getArea(){
        double m=(super.getLen()*this.getWeight());
        System.out.println("长方形的长为"+super.getLen()+",宽为"+this.weight+"\n面积为"+m);
    }



//父类
public abstract class Graph {
    private double len;            //图形的边长
    
    public Graph(double len){
        this.len=len;
    }
    
    //获取长度
    public double getLen(){
        return len;
    }
    
    //抽象面向方法
    public abstract void getArea();
}
View Code

 

posted on 2017-06-15 08:52  星星&之火  阅读(144)  评论(0编辑  收藏  举报