java - 如何使用基本接口引用调用扩展接口函数?
问题描述
对不起,如果我的问题没有任何意义。我会在这里尝试解释一下。假设我有一个这样的基本接口:
public interface SimpleInterface {
public void function1();
}
扩展接口如下:
public interface ExtendedInterface extends SimpleInterface{
public void function2();
}
可以说我有一个实现的类ExtendedInterface
:
public class Implementation implements ExtendedInterface {
@Override
public void function1() {
System.out.println("function1");
}
@Override
public void function2() {
System.out.println("function2");
}
}
现在,function2()
当我得到一个用类SimpleInterface
实例化的基接口 ()时,有什么方法可以调用,如下所示:Implementation
SimpleInterface simpleInterface = new Implementation();
我知道它违背了接口的目的,但它可以让我免于进行大量代码更改。
解决方案
基本上,您必须强制转换为ExtendedInterface
:
SimpleInterface simpleInterface = new Implementation();
ExtendedInterface extendedInterface = (ExtendedInterface) simpleInterface;
extendedInterface.function2();
当然,如果simpleInterface
引用的对象实际上没有实现,则强制转换将失败ExtendedInterface
。这样做的必要性绝对是一种代码味道 - 它可能是您可用的最佳选择,但至少值得考虑替代方案。
推荐阅读
- java - Spring boot考虑定义一个类型的bean,组件扫描不起作用
- excel - 下标超出范围错误,贯穿文件夹中所有文件的宏
- ruby-on-rails - simple_form 接受集合输入的散列
- html - 材料垂直分隔线未显示
- php - HTML/PHP URL Shortener 在 URL 之后 / 在 URL 中通过 ID 重定向
- c# - 正则表达式获取所有给定单词旁边的单词
- c# - C# WCF Web 服务到 C++ DLL 调用
- javascript - 根据对象 ID 在 mongoose 中创建新表
- r - R:[Indicspecies 包] multipatt 函数:从 summary.multipatt 中提取值
- laravel - 状态消息未显示在我的视图中