Pg188-2 覆盖 向上转型

package org.hanqi.array;

public class DongWu {
    
        private String name;
        
        private  String color;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
        
        public void run()
        {
            System.out.print("会跑");
        }
        public void eat()
        {
            System.out.print("会吃东西");
        }
        

}
DongWu类
package org.hanqi.array;

public class TuZi extends DongWu {
    
    public void eat()
    {
        System.out.print("会吃萝卜");
    }
    

}
TuZi类
package org.hanqi.array;

public class TestDongWu {

public static void main(String[] args) {
        
        DongWu d=new DongWu();
        
        d.setName("动物");
        
        d.setColor("有颜色");
        
        System.out.print("一只"+d.getColor()+"的"+d.getName() );
        
        d.run();
        
        d.eat();
        
        System.out.println("");
        
        //子类中覆盖第二个方法    
        TuZi t=new TuZi();
        
        t.setName("兔子");
        t.setColor("白色");
        
        System.out.print("一只"+t.getColor()+"的"+t.getName() );
        t.run();
        
        t.eat();
    
        System.out.println();
    
        //向上转型
        DongWu d1=new TuZi();
        
        d1.setName("狗");
        
        d1.setColor("黑色");
        
        System.out.print("一只"+d1.getColor()+"的"+d1.getName() );
        
        d1.run();
        
        d1.eat();
    }

}
测试类

posted @ 2016-03-10 20:16  1011042043  阅读(125)  评论(0编辑  收藏  举报