简体   繁体   English

如何从不在Java的层次结构中的类调用抽象方法

[英]How to call the abstract method from a class which is not in hierarchy in java

Below is my code. 下面是我的代码。 I have the abstract class Myabatract which has the method myMethod and I have a subclass MySubClass in which I have overridden the myMethod . 我有一个抽象类Myabatract ,它具有方法myMethod并且我有一个子类MySubClass ,其中重写了myMethod In my client class I have a method callMethod from which I want to directly call the myMethod of Myabatract class is this possible? 在我的客户端类中,我有一个方法callMethod ,我想直接从其中调用Myabatract类的myMethod ,这可能吗?

abstract class Myabatract {

public void myMethod() {
    System.out.println("This is from Myabatract");
}

}

class MySubClass extends Myabatract  {
public void myMethod() {
    System.out.println("This is from MySubClass");
    super.myMethod();
}
}


class Client{
public void callMethod(){

}
}

You can create an anonymous implementation of the abstract class . 您可以创建abstract class的匿名实现。 This is particularly easy given the fact that it does not use any abstract methods. 考虑到它不使用任何abstract方法,这一点特别容易。

class Client {
  public void callMethod() {
    Myabatract instance = new Myabatract() { /* nothing to implement*/ };

    instance.myMethod();
  }
}

As a user of the MySubClass type, you have no way to call the Myabatract method because it has been overridden, unless MySubClass were to expose it. 作为MySubClass类型的用户,您无法调用Myabatract方法,因为它已被覆盖,除非MySubClass公开它。 Your only recourse would be to create another method that exposed the super method from within MySubClass (or other child implementations). 您唯一的办法是创建另一个方法,该方法从MySubClass (或其他子实现)中公开super方法。

It's important to note that this will not work: 需要注意的是这不会工作是非常重要的:

class Client {
  public void callMethod() {
    MySubClass instance = new MySubClass() {
      @Override
      public void myMethod() {
        super.myMethod();
      }
    };

    instance.myMethod();
  }
}

super is the non-anonymous class, MySubClass , which means nothing is actually changing. super是非匿名类MySubClass ,这意味着实际上没有任何更改。 Interestingly, this can be worked around in C++ using the scope resolution operator ( :: ). 有趣的是,可以使用范围解析运算符( :: :)在C ++中解决此问题。

It's also worth pointing out that you are calling super.myMethod() in your implementation of MySubClass , which does invoke the Myabatract method. 另外值得指出的是,你在呼唤super.myMethod()在你的实现MySubClass ,它不调用Myabatract方法。

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

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