简体   繁体   English

抽象类非抽象方法调用

[英]Abstract class non abstract method invoke

This seems to be basic question. 这似乎是基本问题。 But worth to clarify before interviews. 但在面试之前值得澄清。

I have a non abstract method in abstract class. 我在抽象类中有一个非抽象方法。 Its concrete class overridden that method. 它的具体类覆盖了该方法。 But I want to call the parent class's original method to invoke rather than overridden method. 但是我想调用父类的原始方法来调用而不是重写方法。 Is there any way to do it ? 有什么办法吗?

As I can understand there's no way to invoke original method ? 据我了解,没有办法调用原始方法吗?

public abstract class Testabstract {

    public void t1() {
        System.out.println("parent");
    }

}


public class Testconcrete extends Testabstract {

    public void t2() {
        System.out.println("child11");
    }

    public void t1() {
        System.out.println("childss");
    }

}

public class Main {

    public static void main(String[] args) {

        Testconcrete a = new Testconcrete();

        a.super.t1();// compile error
        a.t2();

    }
}

No, you can't directly invoke the superclass's overridden method. 不,您不能直接调用超类的重写方法。 This is by design; 这是设计使然; the subclass might add some sort of behavior that is necessary for correctness (such as maintaining some sort of cache or other data structure) or functional requirements (such as logging). 子类可能会添加某种正确性(例如维护某种缓存或其他数据结构)或功能要求(例如日志记录)所必需的行为。 Bypassing the subclass's functionality would put the correctness of the model at risk and breaks the encapsulation that assures it. 绕过子类的功能将使模型的正确性受到威胁,并破坏了确保模型的封装。

super keyword can use only with in the child class. super关键字只能在子类中使用。

For ex you can try doing 对于前,你可以尝试做

 public void t2() {
        super.t1();
        System.out.println("child11");
    }

Casting to Parent also won't work still your underlying element is Child . 强制转换为Parent仍然无法正常工作,您的基本元素是Child

So you cannot access from outside of Child class in a clean way. 因此,您不能以干净的方式从Child类的外部进行访问。 Don't exactly know if they is any naive way to do that. 不完全知道它们是否是幼稚的方式。

Your understanding is correct. 您的理解是正确的。 Without changing one of classes Testabstract or Testconcrete there is no way to invoke the original method on an instance of Testconcrete . 如果不更改TestabstractTestconcrete类之一,就无法在Testconcrete实例上调用原始方法。

I don't think it's even possible to do it with reflection. 我认为反射是不可能的。

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

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