我有一个关于接口和类实现接口的问题。
这是我的代码:
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() ? 这是工作和安全:
((cMyClass)i).iMethod2();感谢帮助。
I have a question about interface and class implementing interface.
This is my code:
interface iMyInterface { public iMethod1(); } public class cMyClass implements iMyInterface { public iMethod1() { // some code } protected iMethod2() { // some code } }I would like to create an instance of iMyInterface as this :
iMyInterface i = new cMyClass(); i.iMethod1();It's ok, but how can I call iMethod2() from my interface instance? Is this working and safe:
((cMyClass)i).iMethod2();Thanks for help.
最满意答案
是的,这将起作用(如果您更改cMyClass的声明以实现iMyInterface )并且它是安全的,只要引用确实引用了cMyClass的实例cMyClass 。
但是,这通常是一个糟糕的主意。 使用接口的全部意义是能够使用任何实现 - 它将抽象与实现分开。 如果您将需要特定的实现,那么您也可以将cMyClass的类型设置为cMyClass 。
因此,假设不是自己调用cMyClass构造函数,而是接收iMyInterface类型的方法参数 - 在这一点上转换为cMyClass是个坏主意,因为它可能是接口的不同实现。
(另外请注意,开始遵循Java命名约定是个好主意,这些约定声明类和接口应该是Pascal包装的,所以请将c和i前缀放在一边。)
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.
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.
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.
(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.)
更多推荐
发布评论