java多态(基础)

(一)父类引用指向子类对象

public class Water {

public void flow(int year) {

System.out.println("I can flow" + i + "years");

}

public void dream() {

System.out,println("I am still water");

}

}

public class River extends Water() {

public void flow(int year) {

System.out,println("I can gallop" + i + "years");

}

public void dream(String str) {

System.out,println(str);

}

}

Water water = new River();

water.flow(3);

Result: I can gallop 3 years

解释:对象water先到类Water中寻找flow方法,存在,但由于子类River中重写了该方法,因此调用的是子类中的flow。这就是动态绑定。

另外,water.dream("River is running")是错误的,即父类引用不能调用父类中没有而子类中有的方法。

water.dream()将打印I am still water.

总结:父类引用指向子类对象主要的作用是利用子类中重写父类的方法。

(二)多态时方法调用原则

class College {

public void show(QiluSoftware o) {

System.out.println("College and QiluSoftware");

}

public void show(College o) {

System.out.println("College and College");

}

}

class QiluSoftware extends College {

public void show(QiluSoftware o) {

System.out.println("QiluSoftware and MIT");

}

}

class MIT extends QiluSoftware {...}

QiluSoftware shanda = new QiluSoftware();

shanda.show(new College()); //到父类中寻找,打印College and College

shanda.show(new MIT());//本类中无,到父类中找,没有,在本类中找MIT的父类,找到,打印QiluSoftware and MIT

总结:调用顺序为this.show(o)->super.show(o)->this.show((super)o)->super.show((super)o)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值