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

多态 static 表示静态 编译的时候只调用Animal类中的eat 不会调用其他类中的eat 不建议用static;

时间:2019-03-16 23:16:57      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:public   父类   class   static   地址   ima   ring   方法   提示   

package cn.zmh.A;

//动物类
public class Animal {
   static void eat(){
       
   }
}

//猫类
 class Cat extends Animal {
   static void eat(){
        System.out.println("猫吃鱼");
    }
}
 
 //狗类
 class Dog extends Animal {
       static void eat(){
            System.out.println("狗吃骨头");
        }
    }

//人类   喂猫喂狗
 class Persosn extends Animal {
        void feedAnimal(Animal anim){

           //打印运行的地址

    //方法前面加上static 这时anim直接提示你变成Animal;
            anim.eat();
        }
    }
 
//测试类
 class TestAnimal {


        public static void main(String[] args){
           //多态写法
           Animal d = new Dog();
           Animal c = new Cat();
            
            Persosn p = new Persosn();
            

      //static 静态 

     // 调用的是Animal类   不会调用Dog类和Cat类的eat;


            //子类的值d赋值给父类Animal
            Animal aimn = (Animal) d;
            p.feedAnimal(aimn);
            
            //子类的值c赋值给父类Animal
            Animal aimn1 = (Animal) c;
            p.feedAnimal(aimn1);
            
        }
    }

多态 static 表示静态 编译的时候只调用Animal类中的eat 不会调用其他类中的eat 不建议用static;

标签:public   父类   class   static   地址   ima   ring   方法   提示   

原文地址:https://www.cnblogs.com/zhangmenghui/p/10544867.html

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