Do you really understand the interface? ? ?

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 protectedan error is reported directly

image-20210317235222474

2. When the interface is implemented, it can only bepublic

Except publicfor 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 privateso that the method can only be used inside the class. That's a ghost of loose coupling.

image-20210317235447384

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 )

image-20210318000412331

image-20210318000424942

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:

image-20210318000627167

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:

image-20210318000846017

image-20210318000859682

At this time, because one returns intand one does not return, the interface implementation intis neither written voidnor written .

image-20210318000931012

And because the type returned by the method cannot be used as a sign of overloading , the following writing method is not helpful...

image-20210318001053987

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.

Guess you like

Origin blog.csdn.net/weixin_44062380/article/details/114957849