java多态猫狗吃骨头_javaSE学习(6):面向对象:多态的两个经典案例(猫狗案例和南北方人案例)...

1.猫狗多态案例

/*

2019年5月19日9点48

@author 潇雷

猫狗案例多态版:

*/

class Animal{

public void eat(){

System.out.println("吃饭!");

}

}

class Dog extends Animal{

public void eat(){

System.out.println("狗吃肉!");

}

public void watchHome(){

System.out.println("狗看家");

}

}

class Cat extends Animal{

public void eat(){

System.out.println("猫吃鱼");

}

public void playGame(){

System.out.println("猫捉迷藏!");

}

}

class DuoTaiTest{

public static void main(String[] args)

{

//定义成狗

Animal a=new Dog();

a.eat();//只能调用eat

System.out.println("--------");

//还原成狗

Dog d=(Dog)a;

d.eat();

d.watchHome();

System.out.println("--------");

//变成猫

a=new Cat();//a指向了新创建的猫的地址

a.eat();

System.out.println("--------");

//还原成猫

Cat c=(Cat) a;

c.eat();

c.playGame();

}

}

2.南北方人饮食文化差异案例

/*

南北方人饮食文化不同的案例

@author 潇雷 时间2019年5月19日10:05

*/

class Person {

public void eat(){

System.out.ptintln("吃饭");

}

}

class SouthPerson extends Person{

public void eat(){

System.out.ptintln("炒个小菜吃吃~");

}

public void business(){

System.out.ptintln("南方人爱经商~");

}

}

class NorthPerson extends Person{

public void eat(){

System.out.ptintln("顿锅菜吃吃~");

}

public void study(){

System.out.ptintln("北方人爱学习~");

}

}

class DuoTaiTest2{

public static void main(String[] args){

//测试

person p=new SouthPerson();

p.eat();//运行看右边,打印出南方人的饮食:炒个小菜吃吃

System.out.println("-------");

SouthPerson sp=(SouthPerson)p;

sp.eat();

sp.business();

System.out.println("-------");

//北方人

p=new NorthPerson();

p.eat();

System.out.println("-------");

//转回北方人

NorthPerson np=(NorthPerson)p ;

np.study();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值