首页 > 解决方案 > 声明父类时不识别接口方法

问题描述

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

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

这是场景:

我的抽象课

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()
    }

}

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

任何提示表示赞赏

问候努里

标签: javaclassinterfaceabstract

解决方案


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

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

唯一的解决方案是投射到IInterface参考点。然后在运行时它将调用方法(如果对象是正确的类型)或 throw ClassCastException


推荐阅读