java 复习笔记——多态性

本文介绍了Java中多态性的概念及其实现方式,并通过具体的代码示例展示了如何使用多态性来实现对象引用的灵活性。文章包括了基类Animal及子类Fish的定义,以及如何通过基类引用调用子类方法。
1)
通过覆盖父类的方法来实现,在运行时根据传递的对象引用,来调用相应的方法。

2)
多态须具备:

[color=red]1. 基类 和各个子类

2. 基类 引用, 指向实例化的子类对象.[/color]

3)

class Animal
{
int height,weight;
void eat()
{
System.out.println("animal eat");
}
void sleep()
{
System.out.println("animal sleep");
}
void breathe()
{
System.out.println("animal breathe");
}
}

class Fish extends Animal
{
int height;
void breathe()
{
System.out.println("fish bubble");
}
}

class Integration
{
static void fn(Animal an)
{
an.breathe();
}
public static void main(String[] args)
{
Fish fh=new Fish();
Animal an;
an=fh;
Integration.fn(an);//或an.breathe();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值