【问题标题】:Interface methods are not recognized when declaring parent class声明父类时不识别接口方法
【发布时间】:2021-03-24 14:42:52
【问题描述】:

我很难给这个主题命名。随意解决这个问题。

但这是我的问题 我有一个抽象类和一个从抽象类扩展的父类。 我希望其中一位父母有另外两种方法并在主类中调用它们。 我想过使用接口来解决这个问题,但这不起作用。

这是场景:

我的抽象类

public abstract class AbstractClass {

    public abstract void method1();
}

我的父类接口

public interface IInterface {
    void method2();
}

我的家长班

public class ParentClass extends AbstractClass implements IInterface{

    @Override
    public void method1() {
        // TODO Auto-generated method stub
    }

    //This is the additional method i want to use
    public void method2() {
    
    }
}

我的主要课程

public class MainClass {

static AbstractClass a;
static boolean condition = true;

public static void main(String[] args) {
    
        if(condition) {
            a = new ParentClass(); // This class should contain the additional method
        }
        else{
            a = new AnotherParentClass();
        }

        a.method2(); <- This does not work. There is only method1()
    }

}

我如何完成这种结构? 抽象类只有父类的基础。 但我也想给父类额外的能力,但想主要使用抽象类,所以我不必创建一个类的多个实例。

感谢任何提示

问候 努里

【问题讨论】:

    标签: java class interface abstract


    【解决方案1】:

    a 是静态类型的AbstractClass,因此您只能看到它的方法。编译器无法知道运行时类型有任何其他方法。

    假设您声明了另一个未实现 IInterface 的类 ParentClass3 extends AbstractClass

    唯一的解决方案是在参考点转换为IInterface。然后在运行时它会调用方法(如果对象是正确的类型)或抛出ClassCastException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多