使用接口 多态 找出符合条件的类

//创建包
package classes;


abstract class Animal{
    public abstract void eat();
}
interface Pet {
        void play();
}
class Dog extends Animal implements Pet{
    public void eat(){
        System.out.println(" Dog eat Bones ");
    }
    public void play(){
        System.out.println(" Play with Dog ");
    }
}

class Cat extends Animal implements Pet{
    public void eat(){
        System.out.println(" Cat eat fish ");
    }
    public void play(){
        System.out.println(" Play with Cat ");
    }
}

class Wolf extends Animal{
    public void eat (){
        System.out.println(" Wolf eat meat ");
    }
}

class TestMain{
    public static void main(String[] args){
        //定义一个Animal类型as数组,储存多个不同子类型对象
        Animal[] as = {new Dog() , new Cat(), new Wolf()}; 
        //调用as数组中所有动物的eat方法
            for(int i = 0 ; i<as.length ; i++){
                as[i].eat();
            }
        //统计数组中宠物的个数
        //统计个数 需要一个计数器
        int count = 0 ;
        //遍历as数组 得到每一个元素
        for(int i = 0; i<as.length ; i++){
            //在这里进行判断 如果Animal数组中有元素实现了宠物接口
            //那么count自增 1 
            if(as[i] instanceof Pet)count++;
        
        }
        //打印count统计个数
        System.out.println(" count: "+count);
        //调用as数组中所有宠物的play方法
        //遍历as数组 得到每一个元素
        for(int i = 0 ; i<as.length ; i++){
            //判断as数组中有那几个实现了宠物接口
            if(as[i] instanceof Pet){
                //如果实现了宠物接口 
                //那就强转为宠物类型
                Pet pet = (Pet)as[i] ;
                pet.play();
            }
        }
    
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值