zoukankan      html  css  js  c++  java
  • JAVA学习--多态使用的一个例子

     1 public class TestAnimal {
     2     public static void main(String[] args) {
     3         TestAnimal t = new TestAnimal();
     4         t.func(new Animal());
     5         t.func(new Dog());
     6         
     7         t.func(new Cat());
     8         
     9     }
    10     public void func(Animal a){//Animal a = new Dog();
    11         a.eat();
    12         a.jump();
    13         
    14         if(a instanceof Dog){
    15             Dog d = (Dog)a;
    16             d.Wang();
    17         }
    18         if(a instanceof Cat){
    19             Cat c = (Cat)a;
    20             c.catchMouse();
    21         }
    22     }
    23 //    public void func(Dog a){
    24 //        a.eat();
    25 //        a.jump();
    26 //    }
    27 }
    28 class Animal{
    29     String name;
    30     int age;
    31     
    32     public void eat(){
    33         System.out.println("进食");
    34     }
    35     public void jump(){
    36         System.out.println("跳");
    37     }
    38 }
    39 class Dog extends Animal{
    40     public void eat(){
    41         System.out.println("狗吃食");
    42     }
    43     public void jump(){
    44         System.out.println("狗急跳墙");
    45     }
    46     
    47     public void Wang(){
    48         System.out.println("汪汪叫");
    49     }
    50 }
    51 
    52 class Cat extends Animal{
    53     public void eat(){
    54         System.out.println("猫吃鱼");
    55     }
    56     public void jump(){
    57         System.out.println("猫跳");
    58     }
    59     public void catchMouse(){
    60         System.out.println("猫抓老鼠");
    61     }
    62 } 
  • 相关阅读:
    网络杂项
    虚拟化
    虚拟化
    ssh
    开机启动命令/服务
    选择表达式
    查询一个表中的重复数据
    oracle逗号分隔函数
    只能为浮点数或整数的正则表达式
    后台模拟弹出上传匡
  • 原文地址:https://www.cnblogs.com/zhangfan94/p/4263278.html
Copyright © 2011-2022 走看看