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

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);
            
        }
    }

猜你喜欢

转载自www.cnblogs.com/zhangmenghui/p/10544867.html