I searched here and in other forums and did not find a good answer. I know that extending classes is not the best practice. And I have to use Interfaces more. my problem is that usually I start creating interfaces, and then move on to abstract classes, because there is always some kind of functionality that I want to implement in a superclass so that I don't have to replicate it in every child class. For example, I have a class class Vehicle and Car and Bike. in the Vehicle class, a lot of functionality can be implemented, such as Move () and Stop (), so it would be best to keep the architecture clean, avoid code repetition and use interfaces instead of Inheritance? Many thanks!
(if you don't know why I'm asking about this, you can read this interesting article: http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html )
Agree with tofutim - in your current example, moving and stopping on the Vehicle is reasonable.
After reading the article - I think that it uses a powerful language to push the point ... remember - inheritance is a tool to help complete the task.
, - / , / ...
- , , , . ... IMoveable + () + () + () + Right()
IFloatable + Dock()
ISink() + BlowAir()
IFly() + () + ()
, .
, car/bike IMoveable.Left() IMoveable.Right(). ... , .
- ... , "".
( " " ) , , - , DRY.
, : ?
. . .
, . , , - .
,1.During .2. , ID, .., .3. . , , .
, , . , ( ) , , (). - , , . , , . Java - - .
, . , - . , 10 90% . 10 ? , , , . , ? external - .
, , extends is evil. ( ), .
extends is evil
.
, . , . , .
, , , :
, . , β 5 , , . , , , . , , , β5. β 5 get-go . (, , , - - ).
? , , . , Move() Stop().
,
, "", , , . , "" Person ( eat() sleep), : Mathematician ( doProblem()) Engineer (buildSomething()), . - , 56 , .
eat()
sleep
doProblem()
Engineer
buildSomething()
IMHO.
, . .
But if we compare an interface with an abstract class, then an abstract class is always more than an interface. An interface is always some aspect of a class - some point of view, not the whole as a class.
Therefore, I do not think that you should avoid inheritance and use it everywhere - there should be a balance.