java中的抽象类和接口最佳实践 [英] abstract classes and interfaces best practices in java

查看:169
本文介绍了java中的抽象类和接口最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以你有一个接口和一个抽象类,它实现了接口中方法的一个子集。你还有一些继承抽象类的类,并给出了抽象类没有给出的方法的实现。

So you've got an interface and an abstract class that implements a subset of the methods in the interface. You've also got some classes that inherit the abstract class and give implementations of the methods the abstract class doesn't give.

那么这里最好的做法是什么?我在谈论的问题如下:

So what's the best practice here? I'm talking about issues like:

1)抽象类应该实现接口还是应该是它的子类?应该每节课吗?在我看来,只是抽象类应该。当然,所有类都可以实现接口,但这似乎是多余的,因为抽象的子代将继承接口,因为它们扩展了抽象类。

1) Should the abstract class implement the interface or should its child classes? Should every class? It seems to me that just the abstract class should. Of course, all of the classes could implement the interface, but that seems redundant because the children of the abstract will 'inherit' the interface because they extend the abstract class.

2)鉴于抽象类实现了接口的一部分,它是否还应该为它没有实现的方法声明抽象方法?在我看来,这是正确的,但在某种程度上这似乎是多余的,因为抽象的孩子需要实现这些方法才能编译。

2) Given that the abstract class implements parts of the interface, should it also declare abstract methods for the methods it doesn't implement? It seems to me like this is right, but in a way this seems redundant because the children of the abstract will need to implement these methods in order to compile.

那么您对最佳实践的理由是什么?问题归结为:我们有一个接口定义了我们想要某些类要做的事情,我们在接口中有一个定义常见行为的方法子集,我们有几种不同的定义方法非常见的行为。最好的解决方法是什么?

So what are your arguments for the best practice? The question boils down to: we've got an interface that defines what we want some classes to do, we've got a subset of the methods in the interface that define common behavior, and we've got a few different ways to define the non-common behavior. What's the best way to lay this out?

推荐答案

应该帮助你的原则id干:不要重复自己( http://en.wikipedia.org/wiki/Don%27t_repeat_yourself )。

The principle that should help you here id DRY: Don't Repeat Yourself (http://en.wikipedia.org/wiki/Don%27t_repeat_yourself).

在这种情况下,DRY意味着你不应该做不必要的工作。

In this context, DRY means that you should not do unnecessary work.

所以对于你的第一个问题抽象类应该实现接口,因为它可以避免在每个具体类中重复implements X子句。

So for your 1st question the abstract class should implement the interface because it saves you from repeating the "implements X" clause at every concrete class.

至于第二个问题,没有必要重复实现它的抽象类中的接口方法。这是多余的工作。此外,当接口演变/更改时,您需要更改抽象类中的对应(抽象)方法,这是一个令人头疼的问题。在某些时候你会错过更新一些方法,具体类需要徒劳地实现这些。

As for the 2nd question, there's no point in repeating the interface methods in the abstract class that implements it. This is redundant work. Moreover when the interface evolves/changes you will need to change the counterparts (abstract) methods at the abstract class which is a headache. At some point you'll miss updating some of the method and the concrete class will need to implement these in vain.

这篇关于java中的抽象类和接口最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆