美文网首页
父类和子类之间方法调用的问题

父类和子类之间方法调用的问题

作者: 从零开始的程序猿生活 | 来源:发表于2020-12-25 10:18 被阅读0次

    Father类

    class Father {
        void fun1() throws Exception {
            System.out.println("父类fun1方法");
            fun3();
        }
        void fun2() throws Exception {
            System.out.println("父类fun2方法");
        }
        void fun3(){
            System.out.println("父类fun3方法");
        }
    }
    

    Son类

    class Son extends Father{
    
        @Override
        void fun2() throws Exception {
            System.out.println("子类fun2方法");
            fun1();
        }
        @Override
        void fun3(){
            System.out.println("子类fun3方法");
        }
    
        void fun4(){
            System.out.println("子类fun4方法");
        }
    }
    

    测试类

    public static void main(String[] args) throws Exception {
        Father b = new Son();
        b.fun2();
        b.fun4();// 编译会报错
    }
    

    问题1:编译为什么报错?

    原因:引用一句话编译看左边,运行看右边,编译的时候看Father ,Father 类中没有fun4()方法,所以会报错。

    问题2:在调用Son类中的fun2()方法时,执行父类的fun1()方法中的fun3()方法是调用的子类重写的方法还是父类的方法呢?

    运行的时候看右边也就是Son类,
    当执行fun2()方法时,
    1、进入的Son执行fun2()方法
    2、内部调用父类的fun1()方法
    3、进入父类的fun1()方法,这是的this是Son实例,直接调用fun3()方法会调用Son类中的fun3()方法。
    // 代码执行结果
    子类fun2方法
    父类fun1方法
    子类fun3方法
    问题3:如果我就想在Father类的fun1()方法中调用父类本身的fun3()方法要怎么调用呢?
    因为当前的this实例对象时Son对象,super是Object对象,所以只能使用反射来实现。
    改下父类的fun1()方法

        void fun1() throws Exception {
            System.out.println("父类fun1方法");
            fun3();
            Method fun3 = this.getClass().getSuperclass().getDeclaredMethod("fun3");
            fun3.invoke(this.getClass().getSuperclass().newInstance());
        }
    

    利用反射获取父类的fun3方法,然后执行。
    // 代码执行结果
    子类fun2方法
    父类fun1方法
    子类fun3方法
    父类fun3方法

    getMethod()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法
    getDeclaredMethod()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法

    相关文章

      网友评论

          本文标题:父类和子类之间方法调用的问题

          本文链接:https://www.haomeiwen.com/subject/nfsbnktx.html