【Java学习笔记】父类引用指向子类对象时方法的调用

来源:互联网 发布:最近很火的网络歌曲女 编辑:程序博客网 时间:2024/06/13 01:47

首先,定义几个类

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没有的方法是不允许调用的

原创粉丝点击