父类引用指向子类对象时方法的调用

首先,定义几个类

class Father{
	public void show(A a){
		System.out.println("Father and A");
	}
	public void show(D d){
		System.out.println("Father and D");
	}
}
class Child extends Father{
	public void show(A a){
		System.out.println("Child and A");
	}
	public void show(C c){
		System.out.println("Child and C");
	}
}
class A{}
class B extends A{}
class C extends B{}
class D extends C{}

下面我们写一些方法来验证一下:

public class Test {
	public static void main(String[] args) {
		Father f1 = new Father();
		Father f2 = new Child();
		f1.show(new A()); //Father and A
		f1.show(new B()); //Father and A
		f1.show(new C()); //Father and A
		f1.show(new D()); //Father and D
		f2.show(new A()); //Child and A
		f2.show(new B()); //Child and A  **
		f2.show(new C()); //Child and A  **
		f2.show(new D()); //Father and D
	}
}

应该就打星号的稍微难理解:
1)f2.show(new B())
    Father类里的show方法参数是由AD,所以B要向上转型为A,然后由于子类Child重写了show(A a)方法,所以调的是子类的这个方法
2)f2.show(new C())
    别看子类有show(C c)方法,调不到有什么用,C先转型为B,但是找不到方法,再转型为A,然后调用的还是子类重写的方法
总的来说,像Father f = new Child()这种语法,f可用的方法就是Father的方法,但是如果Child重写了,果断用重写的,Child独有而Father没有的方法是不允许调用的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值