即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

46_面向对象_19_多态_内存解析

编程语言 qq_21122243 23℃ 0评论
public class Animal {
    String str;
    public void voice(){
        System.out.println("普通动物叫声!");
    }
}

class Cat extends Animal{
    public void voice(){
        System.out.println("喵喵喵");
    }
    public void catchMouse(){
        System.out.println("抓老鼠");
    }
}

class Dog extends Animal {
    public void voice(){
        System.out.println("汪汪汪");
    }
    public void seeDoor(){
        System.out.println("看门!");
    }
}

class Tiger extends Animal {
    public void voice(){
        System.out.println("哇哇哇");
    }
}

class Pig extends Animal {
    public void voice(){
        System.out.println("哼哼哼");
    }
}
public class Test {
    public static void testAnimalVoice(Animal c){
        c.voice();
        if(c instanceof Cat){
        ((Cat) c).catchMouse();
        }
    }
    /*
    public static void testAnimalVoice(Dog c){
        c.voice();
    }
    public static void testAnimalVoice(Pig c){
        c.voice();
    }*/
//javac Test.java
// java Test
        public static void main(String[] args) {
            Animal a = new Cat();
            Cat a2 = (Cat)a;
            testAnimalVoice(a);

        //  a2.catchMouse();

        //  Animal b = new Dog();
        //  Animal c = new Tiger();
        //  testAnimalVoice(b);
        //  testAnimalVoice(c);
        }
}

这里写图片描述


注:this永远指向当前对象!

转载请注明:CodingBlog » 46_面向对象_19_多态_内存解析

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情