1

自己是否应该始终定义接口和抽象类,即使只有 1 个类扩展它们?我从事一些小型 Java 项目已经有一段时间了。我一直看到他们总是在他们编写的每个其他类中创建抽象类和接口。但在几乎所有其他情况下,接口仅由一个类实现,抽象类也仅由另一个类扩展。这是因为多个类没有扩展或实现的范围。因此,根据我的理解,如果我们知道会有很多其他类会使用它,我们就可以拥有接口和抽象类。在上述情况下,我觉得应该直接编写具体的类。并且将来如果需要自己可以修改这些类并创建接口等并加以利用。不知何故,我 99% 确信我对多态性使用的理解达不到标准。请让我知道这些概念的正确用法。

4

3 回答 3

2

如果您将使用多个抽象类和接口,则意味着它们。如果你只计划上一门课,你也不需要。

如果稍后您需要两个子类,您总是可以将原始类转换为接口。

要记住的一件事是编写接口和抽象类是安全的。如果功能是已知的并且已经制作了骨架,那么测试您的类会更容易,并且可以防止错误。

于 2013-07-29T18:54:11.637 回答
0

Interface and single implementation can make sense if you want to provide an API to a 'client'.

What you will do is to design the API first (interfaces), then provide it to your client, without the implementation. I see two advantages :

  • your client can work on his side, knowing all the existing methods in your API : work can be parallelized between your team and your client team.
  • you don't have to provide him with implementation sources, that you want to keep confidential. Implementation can be provided in a separate jar, at runtime.

Also, if you are working on a system where you want to preserve backward compatibility, I would suggest you introduce interfaces as soon as possible in order not to get stuck later.

Otherwise, I would suggest you to introduce interfaces only when you need them, and rely on refactoring tools in order to change your code easily. This will lead you to someting easier to understand. Other developers will thank you for that.

Cheers

于 2013-07-30T10:47:45.463 回答
0

如果您有几个类似的类来实现/扩展接口和抽象类,那么接口和抽象类就很有意义。如果您目前只有一个子类,但您知道可以在某个时候添加更多子类,它们也很有意义。

但是如果你确切地知道永远不会有任何其他类似的类,你就不应该使用它们。那只会减慢程序的速度。

于 2013-07-29T18:59:53.847 回答