鉴于以下课程:
class Example implements Interface1, Interface2 {
...
}
Run Code Online (Sandbox Code Playgroud)
当我使用Interface1以下方法实例化类时:
Interface1 example = new Example();
Run Code Online (Sandbox Code Playgroud)
...然后我只能调用Interface1方法,而不是Interface2方法,除非我施放:
((Interface2) example).someInterface2Method();
Run Code Online (Sandbox Code Playgroud)
当然,为了使这个运行时安全,我还应该用一个instanceof检查包装它:
if (example instanceof Interface2) {
((Interface2) example).someInterface2Method();
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以有一个扩展两个接口的包装器接口,但最后我可能会有多个接口来满足可以由同一个类实现的所有可能的接口排列.有问题的接口并不会自然地相互扩展,因此继承似乎也是错误的.
instanceof/ cast方法是否会破坏LSP,因为我正在询问运行时实例以确定其实现?
无论我使用哪种实现,似乎都会在糟糕的设计或使用中产生一些副作用.