java - 声明父类时不识别接口方法
问题描述
我很难给这个线程命名。随意解决这个问题。
但这是我的问题,我有一个抽象类和一个从抽象类扩展的父类。我希望其中一位父母有另外两种方法并在主类中调用它们。我考虑过使用接口来解决这个问题,但这不起作用。
这是场景:
我的抽象课
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()
}
}
我如何完成这种结构?抽象类只有父类的基础。但我也想给父类额外的能力,但想主要使用抽象类,所以我不必创建一个类的多个实例。
任何提示表示赞赏
问候努里
解决方案
a
是静态类型的AbstractClass
,因此您只能看到它的方法。编译器无法知道运行时类型有任何其他方法。
假设您声明了另一个ParentClass3 extends AbstractClass
没有实现的类IInterface
?
唯一的解决方案是投射到IInterface
参考点。然后在运行时它将调用方法(如果对象是正确的类型)或 throw ClassCastException
。
推荐阅读
- swift - 快速将字符串转换并格式化为字符数组
- swift - 删除 PencilKit 中的内容
- php - 如何扩展 laravel 刀片指令@extends?
- kubernetes-helm - helm push to artifactory 总是抛出 404 错误,找不到 /api/artifactory/helm/charts
- karate - 有没有办法从 karate-config.js 调用包含可重用功能文件路径的变量?
- powershell - Create table with different output
- java - 为什么我的方法不能使用 (String arg, arg2) 而不是 (String arg, String arg2)?
- javascript - 在带有 angular 的 fuse.js 中,我们在哪里传递搜索到的字符串和选项?
- python - 为枚举创建值查找列表
- java - 使用 Apache POI 读取 excel 文件时出现 ClassCastException