Java interface
I won’t talk about why you need to use an interface here. Because most people have been developing for so long, they should have understood the reasons and benefits of using an interface. Isn’t it just the loose coupling set, but have you really considered some issues about the interface? ? .
1. The method in the interface does not need to be declared aspublic
Although there will be no error in writing, it is not necessary at all, because when the interface is implemented, it can only bepublic
Not to mention that the interface method is declared as private
, and protected
an error is reported directly
2. When the interface is implemented, it can only bepublic
Except public
for other types of quasi-error
Besides, if you want to declare an interface method as private
, what's the point of writing this interface?
The purpose of the interface was originally for loose coupling. It is well written private
so that the method can only be used inside the class. That's a ghost of loose coupling.
3. The problem of implementing multiple interfaces with the same name
3.1 The two methods are exactly the same
Two interfaces defined herein, which method own, identical (exactly, referring to 函数名
, 返回值
, 参数类型
, 参数个数
and 不同类型参数的排列顺序
are exactly the same, these conditions, in addition to the return value and the function name, and the remaining three samples, to ensure that the conditions are the same as each function can be overloaded )
In the end, when multiple interfaces are implemented, it is actually equivalent to only implementing one method, which has no effect, and polymorphism can be achieved:
3.2 Only the return type is different
However, if the two interface function names and the number of parameters are the same, only the return value is different . In other words, the condition for distinguishing function overloading is not met , then the compiler will report an error:
At this time, because one returns int
and one does not return, the interface implementation int
is neither written void
nor written .
And because the type returned by the method cannot be used as a sign of overloading , the following writing method is not helpful...
3.3 The interface can have the same name only if the conditions of function overloading are met
As mentioned in 3.1 参数类型,参数个数、不同类型参数的排列顺序
, each of these three conditions can be overloaded. As long as any one of them is satisfied, multiple inheritance and implementation of the interface with the same function name can be realized.