java笔记--day09--关于多态的两个案例(猫狗和老师学生)

本文通过两个实例演示了多态的概念,第一个案例展示了动物类中猫和狗的不同行为,第二个案例则对比了南方人和北方人的饮食习惯差异。文章强调了多态即父类引用指向子类对象,并调用子类方法的核心思想。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 案例1(猫狗):
class Animal{
    public void eat(){
        System.out.println("Animal eat food.");
    }
}

class Cat extends Animal{
    public void eat(){
        System.out.println("Cat like eating fish");
    }
    public void catCatch(){
        System.out.println("Cat like Catching mice.");
    }
}

class Dog extends Animal{
    public void eat(){
        System.out.println("Dog like eating bones.");
    }
    public void guard(){
        System.out.println("Dog guards the door.");
    }
}

class PolymorphismDemo3{
    public static void main(String[] args) {
        Animal c1 = new Cat();//when cat is an animal
        c1.eat();
        System.out.println();
        Cat c2 = (Cat)c1;//Downcasting. back to a cat
        c2.eat();
        c2.catCatch();

        System.out.println();
        System.out.println();

        Animal d1 = new Dog();//when dog is an animal
        d1.eat();
        System.out.println();
        Dog d2 = (Dog)d1;//Downcasting. back to a dog
        d2.eat();
        d2.guard();

    }
}

/*
running result:
Cat like eating fish

Cat like eating fish
Cat like Catching mice.


Dog like eating bones.

Dog like eating bones.
Dog guards the door.
*/
  • 案例2(老师和学生):
class Person{
    public void eat(){}
}

class SouthPerson extends Person{
    public void eat(){
        System.out.println("South person eat rice.");
    }
    public void custom(){
        System.out.println("South person like business.");
    }
}

class NorthPerson extends Person{
    public void eat(){
        System.out.println("North person eat noodles.");
    }
    public void custom(){
        System.out.println("North person like academic research.");
    }
}

class polymorphismDemo4{
    public static void main(String[] args) {
        Person p = new SouthPerson();
        p.eat();
        System.out.println();
        SouthPerson sp = (SouthPerson)p;
        sp.eat();
        sp.custom();
        System.out.println();
        System.out.println();

        p = new NorthPerson();
        p.eat();
        System.out.println();
        NorthPerson np = (NorthPerson)p;
        np.eat();
        np.custom();
    }
}

/*
running result:
South person eat rice.

South person eat rice.
South person like business.


North person eat noodles.

North person eat noodles.
North person like academic research.
*/
  • 总结
    多态其实就是一个父类指向子类的对象,然后对子类的方法的调用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值