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

  • Post author:
  • Post category:其他


首先,定义几个类

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方法参数是由


A





D


,所以


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


没有的方法是不允许调用的



版权声明:本文为LoveHYZH原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。