码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象多态以及转型

时间:2015-05-06 22:51:22      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

 

 

package com_package1;

public class Dog extends Animal{
    
    public void eat()
    {
        
        System.out.println("啃骨头");
    }//将父类中的抽象方法实例化
    public void lookHome()
    {
        System.out.println("看家");
    }//够的特有属性

}
package com_package1;

public class Cat extends Animal {
    public void eat()
    {
        System.out.println("eat fish");
        
    }
    public void catchMouse()
    {
        
        System.out.println("catMouse");
    }
}
package com_package1;

public class Pig extends Animal{
   public void eat()
   {
       
       System.out.println("siliao");
   }
   public void gongDi() {
       System.out.println("gongdi");
    
}
}
package com_package1;

public class DuotaiDemo {
       public static void main(String[]args)
       {
           Pig p  = new Pig();
           Dog d = new Dog();
           Cat c = new Cat();
           method(p);
           method(d);
           method(c);
           
       }
       public static void method(Animal a)
       {    a.eat();
           if(a instanceof Cat)
          
           {Cat c =  (Cat)a;
           c.catchMouse();}
           else if(a instanceof Dog)
           {  Dog d = (Dog)a;
              d.lookHome();
              }
           else
           {Pig p = (Pig)a;
           p.gongDi();}
       }

}

 

 

接口和多态练习

package com_package1;

public class NoteBook {
    public void run()
    {
        
        System.out.println("enable");
        System.out.println("disabble");
    }
    public void useUSB(USB u)
    {
        if(u!=null)
        {
            u.able();
            u.enable();
            
        }
        
    }
}
package com_package1;

public interface USB {
    public void able();
    public void enable();

}
package com_package1;

public class UDisk implements USB {

    @Override
    public void able() {
        // TODO Auto-generated method stub
        System.out.println("disk able");
    }

    @Override
    public void enable() {
        // TODO Auto-generated method stub
     System.out.println("disk enable");        
    }
    


}
package com_package1;

public class Umouse implements USB{

    @Override
    public void able() {
        // TODO Auto-generated method stub
        System.out.println("mouse able");
    }

    @Override
    public void enable() {
        // TODO Auto-generated method stub
        System.out.println("mouse enable");
        
    }
    

}
package com_package1;

public class NoteBookDemo {
    public static void main(String[]args)
    {
        NoteBook nt = new NoteBook();
        nt.run();
    //    nt.useUSB(u);
        nt.useUSB(null);
        nt.useUSB( new UDisk());
        nt.useUSB(new Umouse());
        
    }

}

 

面向对象多态以及转型

标签:

原文地址:http://www.cnblogs.com/mmlovejj/p/4483183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!