简体   繁体   English

在Java中使用子类对象调用父方法

[英]Calling parent method using child class object in Java

Is there a way to call the parent class methods which are overridden by the child class using a child class object?有没有办法使用子类对象调用被子类覆盖的父类方法? I know that you can use super.foo() inside the overridden method to redirect the call to the parent class method but is there a way that doesn't involves going into the child class method first before calling the parent method?我知道您可以在重写的方法中使用 super.foo() 将调用重定向到父类方法,但是有没有一种方法不涉及在调用父方法之前先进入子类方法?

No.不。

If an object of class Child is called to do x() , then in Java, it's the responsibility of its class ( Child ) to supply the correct implementation.如果调用类Child的对象来执行x() ,那么在 Java 中,它的类 ( Child ) 负责提供正确的实现。 So, the Child class is always in charge, and it's the sole decision of the Child class whether to call its parent class method in the process of serving the x() call.因此, Child类始终负责,并且在服务x()调用的过程中是否调用其父类方法由Child类唯一决定。

If you find situations where the child class implementation is not appropriate for servicing the x() call, then that's a bug of this Child.x() method implementation, and you have to fix that implementation to correctly serve the call.如果您发现子类实现不适合为x()调用提供服务的情况,那么这是Child.x()方法实现的一个错误,您必须修复该实现才能正确地为调用提供服务。

If, for some given call parameters, the child class can't tell how to correctly serve the call, then the design of that method (as a contract between caller and callee) is flawed, and you should clean that up, eg make two different methods from x() .如果对于某些给定的调用参数,子类不能告诉如何正确地为调用提供服务,那么该方法的设计(作为调用者和被调用者之间的契约)就有缺陷,您应该清理它,例如制作两个与x()不同的方法。

You don't have to call super.foo() from the child class implementation of foo().您不必从 foo() 的子类实现中调用 super.foo()。

public class Main {

    static class A {
        void foo() {
            System.out.println("A.foo()");
        }
    }

    static class B extends A {
        void foo() {
            System.out.println("B.foo()");
        }
        void bar() {
            super.foo();
        }
    }

    public static void main(String[] args) {
        B b = new B();
        b.bar();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM