Java – abstract classes and interfaces together?

I have some code, some of which are implementing an interface

It feels right, but there is a bit of repetition in childhood - that is, three methods

So this is screaming out using abstract classes

My question is whether there are any disadvantages of using abstract classes and interfaces in the following cases:

>Abstract classes to implement interfaces and subclasses to extend abstract classes > subclasses extend abstract classes and implement interfaces

or

Should abstract classes and interfaces be used together like this?

Solution

It is quite normal to use these two together Consider, for example, abstractlist and abstractmap in JDK

My knee reaction was to let the abstract class implement the interface, and then the concrete class derived from it:

abstract class Base implements TheInterface {
    /* ...shared methods... */
}

class Concrete1 extends Base { }

class Concrete1 extends Base { }

However, the question of raising another possibility reminds me that I do not see much argument against doing so:

abstract class Base {
    /* ...shared methods... */
}

class Concrete1 extends Base implements TheInterface { }

class Concrete1 extends Base implements TheInterface { }

In addition, I can see a parameter that does this. Specifically, it eliminates the coupling between abstract classes and interfaces If you have another class that needs the functions provided by base, but do not need to implement the interface, you can flexibly perform this operation

There is a third option: combination You can't have an abstract class at all, but multiple concrete classes that implement the interface. A common helper class is used in their implementation:

class Helper {
    /* ...shared methods... */
}

class Concrete1 implements TheInterface {
    /* ...uses instance of Helper */
}

class Concrete1 implements TheInterface {
    /* ...uses instance of Helper */
}

This has the same flexibility in another form

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>