Java将接口转换为类 [英] Java cast interface to class
问题描述
我有一个关于接口和类实现接口的问题。
I have a question about interface and class implementing interface.
这是我的代码:
interface iMyInterface {
public iMethod1();
}
public class cMyClass implements iMyInterface {
public iMethod1() {
// some code
}
protected iMethod2() {
// some code
}
}
以创建 iMyInterface
的实例:
iMyInterface i = new cMyClass();
i.iMethod1();
没关系,但如何调用 iMethod2 $ c>从我的接口实例?这是工作和安全:
It's ok, but how can I call iMethod2()
from my interface instance? Is this working and safe:
((cMyClass)i).iMethod2();
感谢您的帮助。
推荐答案
是的,这将工作(如果您更改 cMyClass
的声明以实现 iMyInterface
)并且它是安全的,只要引用真的 是指 cMyClass
的实例。
Yes, that will work (if you change the declaration of cMyClass
to implement iMyInterface
) and it's safe so long as the reference really does refer to an instance of cMyClass
.
但是,这是一个糟糕的主意。使用接口的全部要点是能够使用任何实现 - 它将抽象与实现分开。如果你需要一个特定的实现,你也可以使 i
的类型只是 cMyClass
However, it's a generally bad idea. The whole point of using an interface is to be able to work with any implementation - it's to separate the abstraction from the implementation. If you're then going to require a specific implementation, you might as well make the type of i
just cMyClass
to start with.
因此,假设不是自己调用 cMyClass
构造函数, c $ c> iMyInterface - 这是一个坏主意,转换到 cMyClass
在那一点,因为它可以是一个不同实现接口。
So suppose instead of calling the cMyClass
constructor yourself, you receive a method parameter of type iMyInterface
- it's a bad idea to cast to cMyClass
at that point, as it could be a different implementation of the interface.
(另一个注意事项是,开始遵循Java命名约定是一个好主意,它规定类和接口应该是Pascal-cased - 因此请分开 c
和 i
前缀。)
(On a separate note, it's a good idea to start following Java naming conventions, which state that classes and interfaces should be Pascal-cased - so ditch the c
and i
prefixes.)
这篇关于Java将接口转换为类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!