英文:
How does Interfaces provide 100% abstraction when we can use default and static methods?
问题
如果我们可以在接口中使用默认方法和静态方法,并在其他类中实现它,那么我们怎么能说接口实现了100%的抽象?
英文:
If we can use the default and static methods in the Interface and implement it in other classes, then how can we say that the interface achieve 100% abstraction?
答案1
得分: 2
我们能够说接口实现了100%的抽象吗?
我认为我们仍然可以这样说。或者至少我们可以说,在接口中的 static
和 default
并不会使实现100%抽象变得更加困难。
接口中的 static
方法与类中的 static
方法没有任何区别。在这两种情况下,方法的 API 都是方法体中代码的抽象边界。
对于 default
方法,我们可以提出相同的论点。方法体可能会执行对所有继承自接口的所有子类实现都通用的操作,但细节仍然对调用者隐藏。这就是抽象边界。
default
和 static
方法所做的是允许抽象边界在继承图中进一步实现。如果使用正确,这是一件好事,因为它消除了冗余或重复的代码。
1 - 程序员需要设计和实现一个不会有泄漏抽象的 API。仅仅使用接口并不能解决这个问题。
英文:
> Can we say that the interface achieve 100% abstraction?
I think we can still say that. Or at least we can say that static
and default
in an interface don't make it any harder to achieve 100% abstraction<sup>1</sup>.
A static
method in an interface is no different to a static
method in a class. In both cases, the method API is the abstraction boundary for the code in the method's body.
We can make the same argument for a default
method. The method body may do things that are common to the implementation of all instances of all descendents of the interface, but the details are still hidden from the caller. That is the abstraction boundary.
What default
and static
methods are doing is to allow the abstraction boundary to be implemented further up the inheritance graph. If you are using them correctly, this is a good thing because it is removing redundant or duplicative code.
<sup>1 - It is up to the programmer to design and implement an API to not be a leaky abstraction. Simply using interfaces doesn't address this.</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论